So this is the layout of my file that is being read:
0
0
0
0
0
And this is the my code:
def readfile(path):
file = open(path, 'r')
scorelist = []
for line in file:
line.strip
scorelist.append(line)
return scorelist
l =readfile('highscores.txt')
print(l)
I just want to save those values to a list, but when I print the list my output is:
['0\n', '0\n', '0\n', '0\n', '0']
How do you fix this?
>Solution :
Your code has a few issues:
- You are appending strings to your array, not numbers. To fix this, just call
float()
to convert the values you’re reading into floats. - You never actually call
.strip()
, all you do isline.strip
, which does nothing. This is why the newline characters aren’t being removed. Just fix this typo.
This code should work:
def readfile(path):
scorelist = []
for line in open(path, 'r'):
scorelist.append(float(line.strip()))
return scorelist
l = readfile('highscores.txt')
print(l)