Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading