简体   繁体   中英

Python: Using an input to determine what line to save on

I'm currently working on a task where I must store scores in a text file. This is my code thus far:

def FileHandle():
    score =  str(Name) + ": " + str(correct)
    File = open('Test.txt', 'a')
    File.write(score)
    File.close()

Name = input("Name: ")
correct = input("Number: ")
FileHandle()

My question is, how would I check already existed names in the text file and only add their score, rather than name and score, to the line it existed on?

This is what the file looks like:

Jonathon: 1
Micky: 5

How it would look after adding a score:

Jonathon: 1, 4
Mickey: 5
# The score added here is Jonathon's 4

Attempt:

# Accept scores
name = input("Name: ")
correct = input("Number: ")
if name in grade_book.keys and "," in grade_book.keys <= 2():
    grade_book[name] += ',' + correct
else:
    grade_book[name] = correct

If you are entering many scores at a time, I suggest reading the file into memory and working with things there. Doing an open/close on the file for every score update is very inefficient.

# Read the file into a dictionary
grade_book = {}
File = open('Test.txt', 'r')
for line in File:
    name, scores = line.split(':')
    grade_book[name] = scores.strip()
File.close()
print grade_book

# Accept scores
name = raw_input("Name: ")
while name != "":
    correct = raw_input("Number: ")
    if name in grade_book.keys():
        grade_book[name] += ',' + correct
    else:
        grade_book[name] = correct

    name = raw_input("Name: ")

# Write dictionary back to the file
File = open('Test.txt', 'w')
for name, scores in grade_book.items():
    out_line = name + ':' + scores + "\n"
    File.write(out_line)

File.close()

Unfortunately you would have to go over the file, find the correct line, edit it and write in a temp file and then move that file to original. Best first use a data structure like dict etc. to update scores and finally when done write or persist them.

def filehandle(name,correct):
    temp = open('temp', 'wb')
    with open('Test.txt', 'r') as f:
        for line in f:
            if line.startswith(name):
                line = line.strip() + correct +'\n'
            temp.write(line)
    temp.close()
    shutils.move('temp', 'data.txt')

You need to pass in the parameters while calling the functions.

Name = input("Name: ")
correct = input("Number: ")
filehandle(name, correct)

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