嘿伙计,所以我有一个文本文件,我试图从中读取并接收每个数字字符串 并将其转换为浮点数。但是每当我尝试它时,它都会说“把绳子转换成浮子”。为什么会这样?谢谢!
try:
input_file = open("Dic9812.TFITF.encoded.txt","r")
output_fileDec = open("Dic9812.TFITF.decoded.txt","w")
output_fileLog = open("Dic9812.TFITF.log.txt","w")
except IOError:
print("File not found!")
coefficientInt = input("Enter a coefficient: ")
coefficientFl = float(coefficientInt)
constInt = input("Enter a constant: ")
constFl = float(constInt)
try:
for line in input_file:
for numstr in line.split(","):
numFl = float(numstr)
print(numFl)
except Exception as e:
print(e)
该文件如下所示:
135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0
它最终会打印数字,但最后却说: 无法将字符串转换为float:
答案 0 :(得分:5)
在第二行的末尾,您有一个逗号,因此列表中有一个空字符串。 float('')
引发异常,因此您的错误:
for line in input_file:
for numstr in line.split(","):
if numstr:
try:
numFl = float(numstr)
print(numFl)
except ValueError as e:
print(e)
如评论中所述,请避免捕获Exception
并尝试在try/except
中使用最少的代码行以避免无提示错误。
答案 1 :(得分:0)
输入f
135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0
Python f.py
import sys
for line in sys.stdin.readlines():
fs = [float(f) for f in line.split(",")]
print fs
<强>用法强>
$ python f.py < f
<强>输出强>
[135.0, 201.0, 301.0]
[152.0, 253.0, 36.0, 52.0]
[53.0, 25.0, 369.0, 25.0]