I have a program to store a persons name and their score, in a txt file in python.
for example this is my current code :
name = input(\"Name: \")
score =
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')