读取文本文件并转换字符串

2024-04-25 13:52:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为“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

我做错什么了?


Tags: 代码intxt列表forreadfoo数字
1条回答
网友
1楼 · 发布于 2024-04-25 13:52:25

编辑

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

相关问题 更多 >