简体   繁体   中英

appending to an existing line in a txt file

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 = input("Score: ")

file_name = "student_scores.txt" 

file = open(file_name , 'a') 
file.write(str(name)  + ", " + str(score) + "\n") 
file.close() 

The output txt file is, (name = bob) and (score = 1) :

bob, 1

When i enter another score (2) for the same person (bob) the txt file looks like this:

bob, 1
bob, 2

However how can i change my code, so that the txt file looks like this :

bob, 1, 2

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.

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 eg, 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM