简体   繁体   English

附加到txt文件中的现有行

[英]appending to an existing line in a txt file

I have a program to store a persons name and their score, in a txt file in python. 我有一个程序可以在python的txt文件中存储人员姓名及其分数。

for example this is my current code : 例如,这是我当前的代码:

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() 

The output txt file is, (name = bob) and (score = 1) : 输出的txt文件是(name = bob)和(score = 1):

bob, 1

When i enter another score (2) for the same person (bob) the txt file looks like this: 当我为同一个人(bob)输入另一个分数(2)时,txt文件如下所示:

bob, 1
bob, 2

However how can i change my code, so that the txt file looks like this : 但是我如何更改我的代码,以便txt文件如下所示:

bob, 1, 2

Unfortunately with ordinary text files you will need to rewrite the file contents to insert into the middle. 不幸的是,对于普通的文本文件,您将需要重写文件内容以插入到中间。 You might consider just processing the file to produce the output you want at the end instead of inserting into the middle of the file. 您可能会考虑仅处理文件以在末尾生成所需的输出,而不是插入文件的中间。

You can't append to a line, however, you can overwrite part of the line. 您不能追加到一行,但是,您可以覆盖该行的一部分。 If you leave a bunch of blanks at the end of the line so that you can record up to eg, 5 scores and update the line in place. 如果您在一行的末尾留下一堆空白,那么您最多可以记录5个乐谱并更新该行。 To do this, open the file 'rw' for read-write, then read until you read bob's score line. 为此,请打开文件“ rw”以进行读写,然后进行读取,直到读取bob的得分行为止。 You can then seek backward by the length of bob's line and rewrite it with his new scores. 然后,您可以按鲍勃线的长度向后搜索,并用他的新乐谱重写。

That said, unless there is a particular reason for using a text format you would be better off using a sqlite database file. 就是说,除非有特殊的原因使用文本格式,否则最好使用sqlite数据库文件。

Store the data of the existing file in a dictionary with name as key and list of scores as value. 将现有文件的数据存储在词典中,名称为键,分数列表为值。 This code will store the existing data to a dictionary, add new score to it and write the dictionary to file with proper formatting. 此代码会将现有数据存储到字典中,向其中添加新分数,然后以正确的格式将字典写入文件。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM