[英]How to convert scientific notation value to float
I have txt files in the format:我有以下格式的txt文件:
6.3894e+02 1.7316e+02 6.6733e+02 1.9942e+02 9.8697e-01
6.4355e+02 1.7514e+02 6.8835e+02 2.0528e+02 9.7908e-01
I want to convert all these values into float as in:我想将所有这些值转换为浮点数,如下所示:
638.94 173.16 667.33 199.42 98.697
643.55 175.14 688.35 205.28 97.908
My code is:我的代码是:
import os
for i in os.listdir():
if i.endswith(".txt"):
with open(i, "r+") as f:
content = f.readlines()
for line in content:
f.write(float(line))
You can't update a file in place like that.你不能像这样就地更新文件。 You can use the
fileinput
module for that.您可以
fileinput
使用fileinput
模块。
You need to split the line at whitespace, parse each of the numbers as floats, then write them the way you want.您需要在空格处拆分行,将每个数字解析为浮点数,然后按照您想要的方式编写它们。
You can also use glob()
to match all the .txt
files instead of using os.listdir()
and .endswith()
.您还可以使用
glob()
来匹配所有.txt
文件,而不是使用os.listdir()
和.endswith()
。
import fileinput
from glob import glob
for i in glob("*.txt"):
with fileinput.input(files=i, inplace=True) as f:
for line in f:
nums = map(float, line.split())
print(*nums)
Try something like this for all the rows:对所有行尝试这样的操作:
text = "6.3894e+02 1.7316e+02 6.6733e+02 1.9942e+02 9.8697e-01"
numbers = text.split()
numbers_float = [float(x) for x in numbers]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.