python - 值错误: could not convert string to float: 'r'

标签 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

最佳答案

>>> 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

关于python - 值错误: could not convert string to float: 'r' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16905026/

相关文章:

python - 如何根据数据框 Pandas 中列的特定条件添加一列

python - 如何通过 AWS Cloudwatch 进行全文搜索?

python-2.7 - 从数据框中选择具有非零值的列

c - 使用 read() 函数读取文件

javascript 如何读取本地文件拒绝访问

python - 从 for 循环内部进行递归时出现意外缩进

python - 从文本文件中提取数据并将其写入 csv 或平面文件

python - 使用 Python 查找包含一组关键字之一的句子

python - 获取导致异常的异常描述和堆栈跟踪,全部作为字符串

python - Python 中的 `next(f)` 、 `f.readline()` 和 `f.next()` 有什么区别?