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 …

问题描述:

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?

解决方案 1[最佳方案][1]

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)

解决方案 2:[2]

The whole code can be simplified to just:

def readfile(path):
    with open(path, 'r') as f:
        scorelist = [line.strip() for line in f]
        #scorelist = [int(line.strip()) for line in f]  # for int values
    return scorelist

(It is generally considered to use the with... context manager so you don’t forget to close open files ;) )

参考链接:

Copyright Notice: This article follows StackOverflow’s copyright notice requirements and is licensed under CC BY-SA 3.0.

Article Source: StackOverflow

[1] Michael M.

[2] Damian Satterthwaite-Phillips

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年4月29日
下一篇 2023年4月29日

相关推荐