mandelbug
mandelbug

Reputation: 1818

Writing and Reading to/from a file in python

I would appreciate any help with my homework assignment - It's a simple program for class that is supposed to check for a file, if it exists, it reads the file, and loads the data into the program, so you can list scores, and add more of them. Its supposed to keep only the top 5 scores.

Then when you close the program (by choosing option 0) it should write the top 5 scores to the scores.txt file. I think I got that to work properly, I'm just having trouble getting the program to read and populate the scores file correctly.

Here's my code so far:

scores = []

#Check to see if the file exists
try:
    file = open("scores.txt")
    for i in range(0, 5):
        name = file.readline()
        score = file.readline()
        entry = (score, name)
        scores.append(entry)
        scores.sort()
        scores.reverse()
        scores = scores[:5]
    file.close()
except IOError:
    print "Sorry could not open file, please check path."


choice = None
while choice != "0":

    print    """
    High Scores 2.0

    0 - Quit
    1 - List Scores
    2 - Add a Score
    """


    choice = raw_input("Choice: ")
    print ""

    # exit
    if choice == "0":
        print "Good-bye."
        file = open("scores.txt", "w+")
        #I kinda sorta get this now... kinda...
        for entry in scores:
            score, name = entry
            file.write(name)
            file.write('\n')
            file.write(str(score))
            file.write('\n')
        file.close()

    # display high-score table
    elif choice == "1":
        print "High Scores\n" 
        print "NAME\tSCORE" 
        for entry in scores:
            score, name = entry    
            print name, "\t", score

    # add a score
    elif choice == "2":
        name = raw_input("What is the player's name?: ")
        score = int(raw_input("What score did the player get?: "))
        entry = (score, name)
        scores.append(entry)
        scores.sort()
        scores.reverse()
        scores = scores[:5]     # keep only top 5 scores

    # some unknown choice
    else:
        print "Sorry, but", choice, "isn't a valid choice." 

raw_input("\n\nPress the enter key to exit.")

Upvotes: 0

Views: 2256

Answers (1)

jdi
jdi

Reputation: 92637

You should try writing your file in a Comma-Separated-Value (CSV). While the term uses the word "comma", the format really just means any type of consistent field separator, with each record on one line.

Python has a csv module to help with reading and writing this format. But I am going to ignore that and do it manually for your homework purposes.

Let's assume you have a file like this:

Bob,100
Jane,500
Jerry,10
Bill,5
James,5000
Sara,250

I am using comma's here.

f = open("scores.txt", "r")
scores = []
for line in f:
    line = line.strip()
    if not line:
        continue
    name, score = line.strip().split(",")
    scores.append((name.strip(), int(score.strip())))

print scores
"""
[('Bob', 100),
 ('Jane', 500),
 ('Jerry', 10),
 ('Bill', 5),
 ('James', 5000),
 ('Sara', 250)]
"""

You don't have to sort the list every time you read and append. You can do it once at the end:

scores.sort(reverse=True, key=lambda item: item[1])
top5 = scores[:5]

I realize lambda may be new to you. It is an anonymous function. We use it here to tell the sort function where to find the key for the comparisons. In this case we are saying for each item in the scores list, use the score field (index 1) for comparisons.

Upvotes: 1

Related Questions