When I read a file and append it's contents into a list, why does it add a '/n' to it's values?

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:

  1. You are appending strings to your array, not numbers. To fix this, just call float() to convert the values you’re reading into floats.
  2. You never actually call .strip(), all you do is line.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)

Leave a Reply