使用python从文件读取浮点数 [英] Reading floats from file with python
问题描述
我的输入文件的格式为:
My input file has the form:
5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650
每个数字基本上都在一行中.
where every number is essentially in a line.
我想做的是读取所有浮点数,然后仅将第7到10列附加到数组中.
What I want to do is read all the floats, and then append only columns 7 through 10 to an array.
这是我写的:
T=[]
with open("test.txt", "r") as file1:
for line in file1.readlines():
f_list = [float(i) for i in line.split(",")]
T.append(float(f_list[7]))
T.append(float(f_list[8]))
T.append(float(f_list[9]))
T.append(float(f_list[10]))
当我运行上面的代码时,我得到:
When I run the above I get:
ValueError: could not convert string to float:
我认为 float(i)
部分出了问题,但我找不到解决方法.
I think there's something wrong with the float(i)
part, but I can't find a way around it.
我已经看到人们在这里遇到类似的问题,但是到目前为止,我尝试过的所有修复方法都没有帮助.任何帮助,我们将不胜感激.
I've seen people having similar problems here, but none of the fixes I've tried so far have helped. Any help is greatly appreciated.
推荐答案
没有问题是您的第一行以逗号结尾:
5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650
因此,您要处理仅包含空格的字符串(例如''
).并且 float('')
失败,因为它不是数字(它实际上报告了这一点):
As a result, you want to process a string that only contains spaces (like ' '
). And float(' ')
fails since it is not a number (it actually reports this):
>>> float(' ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
>>> float('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'
但是在打印时根本看不到空格.
But a space simply is invisible when printed.
您可以通过在列表理解中添加 filter语句来解决该问题:
You can solve it by adding a filter statement to the list comprehension:
T = []
with open("test.txt", "r") as file1:
for line in file1.readlines():
f_list = [float(i) for i in line.split(",") if i.strip()]
T += f_list[7:11]
此外,由于没有一行具有7-11的浮点数,因此不会起作用.因此,您将永远不会添加这些浮点数.
Furthermore this will not work since none of the lines has 7-11 floats. So you will never add these floats anyway.
但是,您可以使用以下代码:
You can however use the following code:
with open("test.txt", "r") as file1:
f_list = [float(i) for line in file1 for i in line.split(',') if i.strip()]
T = f_list[7:11]
这将导致 T
等于:
>>> T
[1.053e-09, 1.839e-09, 1.632e-10, 1.959e-12]
这篇关于使用python从文件读取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!