问题描述:
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:
- 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)
解决方案 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