我有一个名为“foo.txt”的文本文件,其中包含一个数字列表,每行一个,例如:
0.094195
0.216867
0.326396
0.525739
0.592552
0.600219
0.637459
0.642935
0.662651
0.657174
0.683461
我现在想将这些数字读入 Python 列表。我的代码如下:
x = []
file_in = open('foo.dat', 'r')
for y in file_in.read().split('\n'):
x.append(float(y))
但这给了我错误:
ValueError: could not convert string to float
我做错了什么?
请您参考如下方法:
编辑:
由 martineau 评论: 您还可以使用 if y: 来消除 None 或空字符串。
原答案:
失败是因为你使用换行符作为分隔符,因此最后一个元素是空字符串
您可以添加 y.isdigit() 来检查 y 是否为数字。
x = []
file_in = open('sample.csv', 'r')
for y in file_in.read().split('\n'):
if y.isdigit():
x.append(float(y))
或
您可以将 read().split("\n") 更改为 readlines()
或
从 y 中删除前导/尾随字符。它处理带有额外空格的行
for y in file_in:
trimed_line = y.strip() # leading or trailing characters are removed
