覆盖文本文件

时间:2015-11-30 19:40:06

标签: python

以下是代码:

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文件中,用户名输入为' name'。我想要做的是,如果同一个人再次进行游戏而另外两个得分产生的话会用新的两个覆盖前两个结果。

这是文本文件的样子:

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

2 个答案:

答案 0 :(得分:1)

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

如果要以想要使用纯文本文件的方式处理此问题,则必须删除包含该名称的行,然后更新。以下功能可能对此有所帮助:

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
}

答案 1 :(得分: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
相关问题