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()
First of all, you have a issue where you write of the scores to the file:
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:
In addition, instead of writing scores in the format
name,score1,score2,..., you end up writing it asname,[score1, score2]because you are writing the raw list object, also in the line: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.
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:
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:
This should do it. Let me know if something doesn't work!