大家好,我有一个试图读取和接收每个数字字符串并将其转换为浮点型的文本文件。但是每次我尝试它时,都会显示“无法将字符串转换为浮点数”。为什么会这样呢?谢谢!
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('')
引发异常,因此出现错误:
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
以免产生静默错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句