[英]How to convert a string into a float when reading from a text file
Hey guys so I have a text file that I am trying to read from and receive every number string and convert it into a float. 大家好,我有一个试图读取和接收每个数字字符串并将其转换为浮点型的文本文件。 But every time I try it, it says "cannont convert string to float". 但是每次我尝试它时,都会显示“无法将字符串转换为浮点数”。 Why is this happening? 为什么会这样呢? Thanks! 谢谢!
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)
The file looks like this: 该文件如下所示:
135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0
It ends up printing the numbers but at the end it says: cannot convert string to float: 最终打印出数字,但最后说:无法将字符串转换为浮点数:
At the end of the second line, you have a comma, so you have an empty string in the list. 在第二行的末尾,您有一个逗号,因此列表中有一个空字符串。 float('')
raise an exception, hence your error: 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)
As said in comments, avoid to catch Exception
and try to have the minimum lines of code in a try/except
to avoid silent errors. 如评论中所述,避免捕获Exception
并尝试在try/except
中使用最少的代码行,以避免产生无提示错误。
Input f
输入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
python f.py
import sys
for line in sys.stdin.readlines():
fs = [float(f) for f in line.split(",")]
print fs
Usage 用法
$ python f.py < f
Output 产量
[135.0, 201.0, 301.0]
[152.0, 253.0, 36.0, 52.0]
[53.0, 25.0, 369.0, 25.0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.