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

时间:2013-06-03 20:10:27

标签: python python-2.7 readfile

所以我正在读取一个文件并将其存储在变量中,当它走到这一行时:

valP=float(listEleVP)

它返回:

ValueError: could not convert string to float: 'r'

这是整个代码:

def main():
    inFile=open('3weightcalc.in','r')
    i=0
    for line in inFile.readlines():
        a=line.split()

        for items in a:
            listEleVP=items[1]
            listEleVS=items[3]
            valP=float(listEleVP)
            valS=float(listEleVS)
            FinVal=float(valP*valS)
            txtA=items [0]
            txtB=items [2]
            print("On ",txtB,txtA,"would weigh ",FinVal,"pounds.")
    inFile.close()
main()

这是输入(.in)文件数据:

Fred 179.0 Luna 0.1654
Layla 131 Mars 0.376
Pat 145.2 Neptune 1.14
END 0 0 0

2 个答案:

答案 0 :(得分:2)

>>> text = """Fred 179.0 Luna 0.1654
... Layla 131 Mars 0.376
... Pat 145.2 Neptune 1.14
... END 0 0 0"""
>>> for line in text.splitlines():
...     a = line.split()
...     for items in a:
...             print items[1], items[3]
... 
r d
7 .
u a
. 6
a l
3
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
IndexError: string index out of range

你应该这样做:

>>> for line in text.splitlines():
...     items = line.split()
...     print items[1], items[3]
... 
179.0 0.1654
131 0.376
145.2 1.14
0 0

答案 1 :(得分:1)

我认为内圈不是必需的:

def main():
    inFile=open('3weightcalc.in','r')
    i=0
    for line in inFile.readlines():
        items=line.split()

        listEleVP=items[1]
        listEleVS=items[3]
        valP=float(listEleVP)
        valS=float(listEleVS)
        FinVal=float(valP*valS)
        txtA=items [0]
        txtB=items [2]
        print("On ",txtB,txtA,"would weigh ",FinVal,"pounds.")
    inFile.close()
main()

问题是在内圈内你迭代split返回的字符串。

希望这有帮助!