appending to an existing line in a txt file

前端 未结 3 601
隐瞒了意图╮
隐瞒了意图╮ 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')
    
    0 讨论(0)
  • 2021-01-26 14:11

    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 e.g., 5 scores and update the line in place. To do this, open the file 'rw' for read-write, then read until you read bob's score line. 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.

    0 讨论(0)
  • 2021-01-26 14:26

    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.

    0 讨论(0)
提交回复
热议问题