0

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
rm-vanda
  • 3,122
  • 3
  • 23
  • 34
Csarg
  • 353
  • 1
  • 4
  • 15
  • 1
    To be honest, a file is not the best storage method for this. Do you have more than one score at a time to save, or are these truly only occasional updates, one score per use of the program? – Prune Oct 16 '15 at 21:54
  • The program needs to save their 3 latest scores .. scored on the test/quiz. For now I just did the example of Name and Score. Needs to be saved. – Csarg Oct 16 '15 at 21:57
  • You should read the file into a data structured, a dict would work. Then update your dict. Then write (overwrite) a new version of the file back out. – RobertB Oct 16 '15 at 22:04

2 Answers2

2

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()
Prune
  • 76,765
  • 14
  • 60
  • 81
  • Thanks. Edited out the while statement and now it works for my purpose. – Csarg Oct 16 '15 at 22:17
  • Oh one more thing, is it possible to get an adverage of someones 3 scores from the 3 numbers? Also how would I limit each person to only 3 scores. – Csarg Oct 16 '15 at 22:20
  • Remember to do your research before posting. The mean is done here: http://stackoverflow.com/questions/7716331/calculating-arithmetic-mean-average-in-python – Prune Oct 16 '15 at 22:26
  • You limit to 3 scores in much the same way: split the list, check its length. If it's already 3 scores long, then handle the problem according to your needs. – Prune Oct 16 '15 at 22:27
  • Would you add an example to your answer? :) – Csarg Oct 16 '15 at 22:28
  • No, but I'll be happy to review yours. That's how StackOverflow works. – Prune Oct 16 '15 at 22:29
  • Added an attempt to my question – Csarg Oct 16 '15 at 22:57
  • ... which you haven't tried to use. That code doesn't execute legally. Check http://stackoverflow.com/help/mcve for posting guidelines. You should give us code and the output you got. Also, we're getting beyond the original topic. Try the hints I gave you, work through the logic you need to add -- and then perhaps post a new question, if needed. – Prune Oct 16 '15 at 23:07
1

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)
garg10may
  • 5,794
  • 11
  • 50
  • 91
  • 1
    I don't think this would work. Opening with 'a' opens for appending. Then you try to read from it? – RobertB Oct 16 '15 at 22:00