0

I have changed a text file's contents, named 'HighScores.txt', into a list and sorted it using this code:

scores = []

with open("HighScores.txt") as f:
    for line in f:
        name, score = line.split(',')
        score = int(score)
        scores.append((name, score))

scores.sort(key=lambda s: s[1])

The text file looks like this:

hank, 11

jayda, 15

chris, 12

How can I turn this list back into string so I can write it back into a txt file?

First Implementation of a fix was:

f = open("HighScores.txt", 'r+')

for t in ((name, score)):
    f.write(' '.join(str(s) for s in t) + '\n')

Error:

File "C:\Users\samiv\Desktop\Computer Science-20190310T115417Z-001\Computer Science\Coding Project - Copy.py", line 102, in game
f.write(' '.join(str(s) for s in t) + '\n')

TypeError: 'int' object is not iterable

  • Hi, could you post the code you have tried so far? – Raquel Guimarães Mar 10 '19 at 14:08
  • @RaquelGuimarães Link 1: https://stackoverflow.com/questions/8366276/writing-a-list-of-tuples-to-a-text-file-in-python - I've tried this but I don't know if I have implemented this into my code correctly – Sam Ivuerah Mar 10 '19 at 14:13
  • Can you add the code you implemented and the error you are getting to the question? It helps learning from what you tried rather then just getting the correct answer and moving on to the next problem without fully understanding the current one – Raquel Guimarães Mar 10 '19 at 14:16
  • @RaquelGuimarães Done – Sam Ivuerah Mar 10 '19 at 14:37

1 Answers1

0

Try to add this code after last line:

lines = []
for tup in scores:
    s = tup[0] + ', ' + str(tup[1]) + '\n'
    lines.append(s)

with open('result.txt', 'w') as f:
    f.writelines(lines)

To sort in descending order change parameter like this:

scores.sort(key=lambda s: s[1], reverse=True)
DrBender
  • 16
  • 3