我有以下两个代码:
1。
f=open("file.csv","r")
data=f.read()
f.close()
for line in data.split("\n"):
for d in line.split(","):
print(float(d))
2。
f=open("file.csv","r")
data=f.read()
f.close()
for line in data.split("\n"):
for d in line.split(","):
float(d)
第一个代码运行正常,但是第二个代码给出错误:
ValueError:无法将字符串转换为浮点数:
第二个代码有什么问题?
这是文件的前两行:
0,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,0 0,49.805,69.3666,78.4413,83.2828,86.1354,87.9128,89.0309,89.6942,90.0045,90.0045
答案 0 :(得分:0)
您唯一的“空”字段是最后换行符之后的文件结尾。我使用以下代码进行诊断。但是,我无法使该代码顺利通过。甚至您的第一个版本也会引发异常。
f=open("file.csv","r")
data=f.read()
f.close()
for line in data.split("\n"):
for d in line.split(","):
print('|' + d + '|')
print(float(d))
print("----------------------")
这导致
|0|
0.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|100|
100.0
|0|
0.0
----------------------
|0|
0.0
|49.805|
49.805
|69.3666|
69.3666
|78.4413|
78.4413
|83.2828|
83.2828
|86.1354|
86.1354
|87.9128|
87.9128
|89.0309|
89.0309
|89.6942|
89.6942
|90.0045|
90.0045
|90.0045|
90.0045
----------------------
||
Traceback (most recent call last):
File "so.py", line 7, in <module>
print(float(d))
ValueError: could not convert string to float:
解决方案
使用with
语句,一次只输入一行:
with open("file.csv","r") as f:
for line in f:
for d in line.split(","):
print(float(d))
我认为这为您提供了所需的功能。