[英]Reading floats from file with python
我的输入文件有以下形式:
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
每个数字基本上都在一条线上。
我想要做的是读取所有浮点数,然后仅将第7列到第10列附加到数组中。
这是我写的:
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]))
当我运行以上内容时,我得到:
ValueError: could not convert string to float:
我认为float(i)
部分有问题,但我无法找到解决方法。
我看到人们在这里遇到类似的问题,但到目前为止我所尝试过的修复都没有帮助。 任何帮助是极大的赞赏。
没问题是你的第一行以逗号结尾 :
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(' ')
失败,因为它不是一个数字(它实际上报告了这个):
>>> 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'
但是印刷时空间简直是看不见的。
您可以通过向列表推导添加过滤器语句来解决此问题:
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浮动。 所以你永远不会添加这些花车。
但是,您可以使用以下代码:
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]
您的问题是,当您拆分line
,结果列表很可能包含空格。 这会导致float()
失败。 您需要首先通过测试元素是否实际是有效的浮点数来清理拆分列表。 例如:
>>> def is_float(n):
try:
float(n)
return True
except:
return False
>>>
>>> line = '5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,'
>>> lst = [float(n) for n in line.split(',') if is_float(n)]
>>> lst
[5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408]
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.