2015-11-30 159 views
0

下面是代码:覆盖文本文件

import random 
import sys 
name = input("What is your name: ") 
tri = 0 

def rep(): 
    score = random.randint(1,10) 
    total = 0 

    print ("score is",score,) 
    total = +score 

    file = open("1.txt","a") 
    file.write(str(name + " = ")) 
    file.write(str(total)) 
    file.write("\n") 
    file.close() 
    tri = +1 
rep() 

while tri > 2: 
    sys.exit 
else: 
    print(rep()) 

所以这段代码做什么,是为用户生成一个随机的得分2次,然后是得分保存到下的用户名.txt文件,其作为'名字'被输入。我想要做的是,如果同一个人再次进行游戏,并且另外两个得分在那里生成,它会用新的两个覆盖前两个结果。

这里是文本文件会是什么样子:

Tom = 2 
Tom = 7 
Chrissy = 3 
Chirssy = 10 
John = 4 
John = 9 

如果用户“汤姆”做游戏这个时候再次获得5和3,文本文件应该看起来像下面这样:

Chrissy = 3 
Chirssy = 10 
John = 4 
John = 9 
Tom = 5 
Tom = 3 

在它只是不断增加的分值这样的这一现状:

Tom = 2 
Tom = 7 
Chrissy = 3 
Chirssy = 10 
John = 4 
John = 9 
Tom = 5 
Tom = 3 
+0

该文件是否会被读取到程序之外,还是严格用于存储程序数据? –

+0

它会在程序外读取是的。 – KryptoModz

+0

你有没有考虑使用XML或JSON而不是纯文本? –

回答

1

的Fi第一条评论是,使用上下文管理器进行文件操作是一个非常好的主意,这将确保文件资源得到正确处理。出于这个原因,我在代码中使用它,我建议你也这样做。

如果你打算以这种方式来处理这个问题,你想使用纯文本文件,你必须删除包含该名称的行然后更新。如下面的函数很可能要在这里帮助:

def remove_old_names(name, filename): 
    """Remove a line containing a specific name""" 
    with open(filename, 'r') as old_file: 
     lines = old_file.readlines() 

    with open(filename, 'w') as new_file: 
     for line in lines: 
      if name not in line: 
       new_file.write(line) 

再后来,当你可以清除旧名称,然后追加到文本文件:

remove_old_names(name, filename) 
with open("1.txt","a") as results: 
    results.write(str(name + " = ")) 
    results.write(str(total)) 
    results.write("\n") 

注意使用"a"这里以追加模式打开文件。如果用"w"打开,则最终可能会截断该文件。现在

,如果我是在一个更加结构化的方式来处理这一点,我会创建一个存储数据字典:

results = dict() 
results["bob"] = 2 

如此反复的其他用户名。然后我会使用pickleJSON库将此字典序列化为一个文件。

例如使用JSON库,你得到的东西是这样的:

import json 
test = { 
    "bob": 1, 
    "joe": 2, 
    "jane": 3, 
    } 
print(json.dumps(test, sort_keys=True, indent=4)) 

输出:

{ 
    "bob": 1, 
    "jane": 3, 
    "joe": 2 
} 
+0

似乎他只想覆盖文件的一部分,而不是整个文件。 –

+0

文本文件确实包含了其他用户的结果,而不仅仅是玩家结果。 – KryptoModz

+2

@KryptoModz你打算使用'pickle','json'还是其他类似的东西?这些是更强大的数据序列化选项。 – shuttle87

0

这是一个简单的文件格式,只是做手工。一个问题是,文本文件并不是真正存储为行,所以你不能只修改一行。一旦你改变了一行,之后的所有内容都必须重写到文件中。如果文件不是太大,你只需将所有内容都读入列表中,然后解决。

import random 

def rep(name, score1, score2): 
    try: 
     # read entire file into list 
     with open('1.txt') as fp: 
      lines = fp.readlines() 
    except FileNotFoundError: 
     lines = [] 

    name_lower = name.lower() 
    for index, line in enumerate(lines): 
     if line.split('=')[0].strip().lower() == name_lower: 
      # found our match... next line had better be the same player 
      if lines[index+1].split('=')[0].strip().lower() != name_lower: 
       raise RuntimeError("File corrupted") 
      # replace user in the list 
      lines[index] = "{} = {}\n".format(name, score1) 
      lines[index + 1] = "{} = {}\n".format(name, score2) 
      # no need to process further 
      break 
    else: 
     # add new user 
     lines.append("{} = {}\n".format(name, score1)) 
     lines.append("{} = {}\n".format(name, score2)) 

    with open('1.txt', 'w') as fp: 
     fp.writelines(lines) 

name = input("what is your name: ") 
rep(name, random.choice(range(100)), random.choice(range(100))) 
print(open('1.txt').read()) # debug 
+0

这是完美的!但是,如何阻止它在python中输出其他用户分数? – KryptoModz

+0

我不确定你的意思是...你想保留所有的分数,但只显示一个用户?你可以做同样的事情,只需打印匹配的行而不是更新它们。 – tdelaney

+0

有没有办法,我可以私下要求你帮忙吗? – KryptoModz