Python saving to file with limitations

91 Views Asked by At

I have a code set up to allow only 3 scores from a particular user saved in a text file. But I am struggling to make this work. pname is the variable for the persons name, and the amount they got right is stored under the variable correct. I am also trying to add the time they took which I am using the variable etime for. I have the basis down but can't fix the errors or make this work as I tried to adapt this from another answer to a different question. Thank you.

                SCORE_FILENAME  = "Class1.txt"
                MAX_SCORES = 3

                try: scoresFile = open(SCORE_FILENAME, "r+")
                except IOError: scoresFile = open(SCORE_FILENAME, "w+") # File not exists
                actualScoresTable = []
                for line in scoresFile:
                    tmp = line.strip().replace("\n","").split(",")
                    actualScoresTable.append({
                                            "name": tmp[0],
                                            "scores": tmp[1:],
                                            })
                scoresFile.close()

                new = True
                for index, record in enumerate( actualScoresTable ):
                    if record["name"] == pname:
                        actualScoresTable[index]["scores"].append(correct)
                        if len(record["scores"]) > MAX_SCORES:
                            actualScoresTable[index]["scores"].pop(0) # OR del actualScoresTable[index]["scores"][0]
                        new = False
                        break
                if new:
                    actualScoresTable.append({
                                             "name": pname,
                                             "scores": correct,
                                             })

                scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
                for record in actualScoresTable:
                    scoresFile.write( "%s,%s\n" % (record["name"], ","(record["scores"])) )
                scoresFile.close()
1

There are 1 best solutions below

1
noahbkim On

First of all, you have a issue where you write of the scores to the file:

...
scoresFile.write( "%s,%s\n" % (record["name"], ","(record["scores"])) )
...

This line raises a TypeError because of the ","(record["scores]). In order to fix this, simply remove the ",", which appears to be a typo.

After that, there is a semantic error in your overwriting of current scores. For one, you read the already entered scores as strings:

...
tmp = line.strip().replace("\n","").split(",")
actualScoresTable.append({
                        "name": tmp[0],
                        "scores": tmp[1:],
                        })
...

In addition, instead of writing scores in the format name,score1,score2,..., you end up writing it as name,[score1, score2] because you are writing the raw list object, also in the line:

...
scoresFile.write( "%s,%s\n" % (record["name"], ","(record["scores"])) )
...


Next, to fix the issue that causes the program to incorrectly output the scores, you have to change a couple of things. For one, you have to make sure that when you take the scores from the file, you change them into integers.

...
for line in scoresFile:
    tmp = line.strip().replace("\n","").split(",")

    # This block changes all of the scores in `tmp` to int's instead of str's
    for index, score in enumerate(tmp[1:]):
        tmp[1+index] = int(score) 

    actualScoresTable.append({
                            "name": tmp[0],
                            "scores": tmp[1:],
                            })
...

After that, you also have to make sure that when you create a new entry, even if there is only one score you store it in a list:

...
if new:
    actualScoresTable.append({
                             "name": pname,
                             "scores": [correct], # This makes sure it's in a list
                             })
...

Finally, to make sure that the program outputs the scores in the correct format, you have to convert them into strings and put commas in between them:

...
for record in actualScoresTable:

    for index, score in enumerate(record["scores"]):
        record["scores"][index] = str(score)

    # Run up `help(str.join)` for more information
    scoresFile.write( "%s,%s\n" % (record["name"], ",".join(record["scores"])) )
...


This should do it. Let me know if something doesn't work!