appending to an existing line in a txt file

前端 未结 3 657
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 13:45

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 =         


        
3条回答
  •  花落未央
    2021-01-26 14:04

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

提交回复
热议问题