没问题是你的第一行以逗号结尾:
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 "", line 1, in
ValueError: could not convert string to float:
>>> float('a')
Traceback (most recent call last):
File "", line 1, in
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]