2013-06-03 257 views
0

我有下面的代码有问题:ValueError异常:无法将字符串转换为float:

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: 

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

+0

元素的表示(提示:'repr()')是...? –

+0

该表示是'' –

回答

1

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

+0

但为什么它可以用于其他值?将4改为3,2或1确实有效......对于数字3,表示为'9',对于元素2则为'1' –

+0

这是因为'行[3]'是'9','line [2]'是''''。而'line [0]'是''a''。 –

+0

好的,我明白你的回应。它认为“9”是内在的东西,但它只是指字符串。 'line = line.split()'是诀窍。谢谢! –

相关问题