[英]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.