I'm making a quiz which requires to import the users name and score to the text file. I then check if the users score has already been submitted in the quiz so I can append the score to that name instead of creating a new set of data. This needs to be able to append THREE scores and then to remove the first score, second=first, third=second, score=third.
if classs == "1":
text_file = open("Class1.txt", "r")
data = text_file.read()
text_file.close()
if name in data:
combdata = (name,score)
else:
text_file = open("Class1.txt","a")
text_file.write(str(name) +","+ str(score)+"\n")
text_file.close()
Here is the code trying to search the file and append the score of the user to that name set.
liste = []
liste.append(data)
for line in data:
for name in line:
liste.append(score)
print(liste)
break
However, the score is appended like this
['Dion,0\nJarrod,1\nJake Bing,6\nFat,0', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
When you append something to a list it is added at the end of that list. So in your case you need to re-write your file in order to append the new score to the line you want. So I suppose you would need a function that searches for a certain name in the file and adds the new score in a new file:
def searchName(name, score):
with open(fileName, 'r') as f:
data = f.read().split('\n')
with open(newFileName, 'w') as newFile:
for line in data:
if name in line:
line+=(',') + str(score) + (',')
newFile.write(line + '\n')
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments