all, I am learning Python
, and I am wondering how to read a list of tuples, which stored in a txt
file, as in the following case:
I have a txt
file called scores.txt
with the following format:
('name1', 8)
('name2', 2)
('name3', 4)
...
Now I want to read scores.txt
into a list say scores
, so that I can sort the scores in descending order, and do some further processing. I am wondering how to do that.
This is a practise for maintaining a high scores list stored in a txt
file. A function is needed for reading the scores from the file, and appending a new score each time the function is invoked. The list of scores needs to be sorted before saving back in the txt
file (score.txt
). If score.txt
does not exist before hand, it will be created first. I borrowed a piece of code somewhere for reference and had a working solution is:
def high_score(score):
"""Records a player's score and maintains a highscores list"""
# no previous high score file
try:
with open("high_scores.txt", "r") as f:
high_scores = [ast.literal_eval(line) for line in f]
except FileNotFoundError:
high_scores = []
#add a score // Do current stuff for adding a new score...
name = input("What is your name? ")
entry = (name, score)
high_scores.append(entry)
high_scores.sort(key = lambda x: -x[1])
high_scores = high_scores[:5] # keep only top five
# write scores to high_scores.txt
with open("high_scores.txt", "w") as f:
for score in high_scores:
f.write(str(score) + "\n")
The problem for me was in how to convert the strings stored in high_scores.txt
to int
for saving the (name, score)
tuple in high_scores
. And it has been resolved by using ast
module's literal_eval
utility function.