0

I am trying to create leaderboard for my game. After the game ends, it asks for name and calculates score. However, when I write the Name and Score to the leaderboard.txt file and i try to import them back again, I cannot convert the number back to int from string. I need to convert it back to int so that i can sort the leaderboard by the most score achieved, or do I?

score = 5
name = "Adam"

file = open("leaderboard.txt", "a+")
file.write(name+" ")
file.write(str(score)+"\n")
file.close()

file = open("leaderboard.txt", "r")

list_of_lists = []
for line in file:
  list_line = line.split()
  list_of_lists.append(list_line)

for x in range(0,len(list_of_lists)):
  if list_of_lists[x][1].isdigit == True:
    x = int(x)

print(list_of_lists)

This does not work, the number stays string however no errors appear. I really dont know what I am missing. Is this even a right way of writing name and score to .txt file? Is there a better way to think about this? I am really desperate for help.

  • Does this answer your question? [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int) – Mitch Oct 12 '20 at 18:39
  • 1
    You're converting the wrong thing. You actually want to convert `list_of_list[x][1]` to `int`. Then, you need to actually set the list element for it to update the list. `x = int(x)` is wrong. Do `list_of_list[x][1] = int(list_of_list[x][1])` – Pranav Hosangadi Oct 12 '20 at 18:49

1 Answers1

0

It's almost always best to do your transforms to the format most convenient for the remainder of your code as close to the ingress point as possible. Your code wants there to be a string and an integer. Do that conversion as you're reading the data in from the file, before adding it to the list_of_lists structure:

score = 5
name = "Adam"

file = open("leaderboard.txt", "a+")
file.write(name+" ")
file.write(str(score)+"\n")
file.close()

file = open("leaderboard.txt", "r")

list_of_lists = []
for line in file:
    list_line = line.split()
    list_line[1] = int(list_line[1])  # This is the new code
    list_of_lists.append(list_line)

print(list_of_lists)

In so doing, your internal data structure contained in list_of_lists will contain exactly what the rest of the program needs; no need for subsequent transformations. You'll notice my example omits your second for loop; we handled the transform on initial read.

int is the new concept here. But by doing it within your file read loop, you avoid needing to do additional post-processing in a subsequent loop.

As a separate note, it's usually a good idea to have some idea of what you want to have happen if a line in your input file doesn't meet expectations; input validation. For example, you may want to quietly skip blank lines, and you may want to emit a warning to STDERR, and then skip overr any lines that don't follow the "string[space]integer" format.

DavidO
  • 13,812
  • 3
  • 38
  • 66