我有一个程序可以将一个人的姓名及其分数存储在 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
当我为同一个人(鲍勃)输入另一个分数(2)时,txt 文件如下所示:
bob, 1
bob, 2
但是我如何更改我的代码,使 txt 文件看起来像这样:
bob, 1, 2
将现有文件的数据存储在字典中,以名称作为键,以分数列表作为值。此代码会将现有数据存储到字典中,向其中添加新分数,并以正确的格式将字典写入文件。
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')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)