如何在Python中打开文件并从文件中读取浮点数(如果是字符串格式)?我还想更改每个浮点数的值,并用新值重写文件。
答案 0 :(得分:15)
假设每行有一个浮点数:
with open("myfile") as f:
floats = map(float, f)
# change floats
with open("myfile", "w") as f:
f.write("\n".join(map(str, floats)))
如果您想要更多格式控制,请使用format
method字符串。例如,每个句点后只会打印3位数字:
f.write("\n".join(map("{0:.3f}".format, floats)))
答案 1 :(得分:4)
“float()”函数接受字符串作为输入并将它们转换为浮点数。
>>> float("123.456")
123.456
答案 2 :(得分:2)
def get_numbers():
with open("yourfile.txt") as input_file:
for line in input_file:
line = line.strip()
for number in line.split():
yield float(number)
然后在完成后再写回来
以及作为较短版本(未经测试,从头部书写)
with open("yourfile.txt") as input_file:
numbers = (float(number) for number in (line for line in (line.split() for line in input_file)))
答案 3 :(得分:0)
如果你想读取input_num浮动:
import numpy as np
import struct
float_size=4
np.array(struct.unpack('<'+str(input_num)+'f',
fin.read(float_size*input_num)))