2016-05-21 16 views
0

我有一個程序來存儲人名和他們的分數,在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文件是,(名稱= BOB)和(評分= 1):

bob, 1 

當我進入另一個得分( 2)同一個人(BOB)txt文件看起來是這樣的:

bob, 1 
bob, 2 

但是我怎樣才能改變我的代碼,這樣txt文件LO如下所示:

bob, 1, 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') 
0

不幸的是,對於普通的文本文件,您需要重寫文件內容以插入到中間。您可能會考慮只處理文件以在最後生成所需的輸出,而不是插入到文件的中間。

0

您不能附加到一行,但是,您可以覆蓋部分行。如果您在該行末尾留下一堆空白,以便您可以記錄最多5個分數並更新該行。爲此,打開文件'rw'進行讀寫,然後閱讀,直到閱讀bob的分數線。然後,您可以通過bob的長度向後尋找,並用他的新分數重寫它。

也就是說,除非有使用文本格式,你會使用SQLite數據庫文件會更好特殊的原因。