ValueError:无法将字符串转换为float:

时间:2013-06-03 19:48:29

标签: string python-2.7 floating-point

我遇到以下代码的问题:

inputf = open('test.dat', 'r')
lines = inputf.readlines()
rico_clus_e = []
for line in lines:
    line.split()
    print line
    if (line[0] != '#'):
        rico_clus_e.append(float(line[4]))
inputf.close()

我的test.dat文件是:

# specn rico_all        rico_all_e  rico_clus   rico_clus_e rico_farclust   rico_far_e  extin
a119        1.07038692  0.11109547  0.61473431  0.15063627  0.32590239      0.14777812  0.207

这会在我的终端中提供以下输出:

# specn rico_all        rico_all_e  rico_clus   rico_clus_e rico_farclust   rico_far_e  extin

a119        1.07038692  0.11109547  0.61473431  0.15063627  0.32590239      0.14777812  0.207

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    rico_clus_e.append(float(line[4]))
ValueError: could not convert string to float: 

我对此很困惑。它与空间无关,我检查了所有这些。如果你改变4乘1,2或3这是有效的,所以它必须与test.dat文件有关,但我似乎无法弄清楚如何。我正在使用python 2.7.3。

1 个答案:

答案 0 :(得分:1)

line.split()本身对line没有任何作用。您必须存储方法调用的结果并使用它。

相关问题