嘿家伙所以我有一个文本文件,我试图从中读取并接收每个数字字符串并将其转换为浮点数.但是每当我尝试它时,它都会说"把绳子转换成浮子".为什么会这样?谢谢!
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)
Run Code Online (Sandbox Code Playgroud)
该文件如下所示:
135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0
Run Code Online (Sandbox Code Playgroud)
它最终打印数字,但最后它说:不能将字符串转换为浮点数:
在第二行的末尾,您有一个逗号,因此列表中有一个空字符串.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)
Run Code Online (Sandbox Code Playgroud)
如评论中所述,避免捕获Exception并尝试在a中使用最小代码行try/except以避免无提示错误.
| 归档时间: |
|
| 查看次数: |
6432 次 |
| 最近记录: |