附加到txt文件中的现有行

时间:2016-05-21 19:21:40

标签: python python-3.x text file-io

我有一个程序来存储人名和他们的分数,在python的txt文件中。

例如这是我当前的代码:

name = input("Name: ")
score = input("Score: ")

file_name = "student_scores.txt" 

file = open(file_name , 'a') 
file.write(str(name)  + ", " + str(score) + "\n") 
file.close() 

输出txt文件是,(name = bob)和(score = 1):

bob, 1

当我为同一个人(bob)输入另一个分数(2)时,txt文件如下所示:

bob, 1
bob, 2

但是,如何更改我的代码,以便txt文件如下所示:

bob, 1, 2

3 个答案:

答案 0 :(得分:0)

不幸的是,对于普通的文本文件,您需要重写文件内容以插入到中间。您可以考虑只处理文件以在最后生成所需的输出,而不是插入到文件的中间。

答案 1 :(得分:0)

您不能追加到某一行,但是,您可以覆盖部分行。如果你在行尾留下一堆空白,这样你就可以录制最多5个分数并更新到位。要执行此操作,请打开文件'rw'进行读写,然后读取,直至读取bob的得分线。然后你可以按照鲍勃线的长度向后搜索并用他的新分数重写它。

尽管如此,除非使用文本格式有特殊原因,否则最好使用sqlite数据库文件。

答案 2 :(得分:0)

将现有文件的数据存储在名称为键的字典中,并将分数列表作为值。此代码将现有数据存储到字典中,为其添加新分数,并使用正确的格式将字典写入文件。

import os
from collections import defaultdict


def scores_to_dict(file_name):
    """Returns a defaultdict of name / list of scores as key / value"""
    if not os.path.isfile(file_name):
        return defaultdict(list)
    with open(file_name, 'r') as f:
        content = f.readlines()
    content = [line.strip('\n').split(', ') for line in content]
    temp_dict = {line[0]: line[1:] for line in content}
    d = defaultdict(list)
    d.update(temp_dict)
    return d


name = input("Name: ")
score = input("Score: ")

d = scores_to_dict('student_scores.txt')
d[name].append(score)

with open('student_scores.txt', 'w') as f:
    for k, v in d.items():
        f.write(', '.join([k] + v) + '\n')
相关问题