5

python - 当文件为字符串格式时,如何打开文件并从文件中读取浮点数?我还想更改每个浮点数的值并用新值重写文件。

4

4 回答 4

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方法。例如,这只会在每个句点后打印 3 位数字:

    f.write("\n".join(map("{0:.3f}".format, floats)))
于 2012-06-15T15:09:47.550 回答
4

“float()”函数接受字符串作为输入并将它们转换为浮点数。

>>> float("123.456")
123.456
于 2012-06-15T15:07:32.417 回答
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)))
于 2012-06-15T15:09:06.930 回答
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)))
于 2017-05-19T13:26:43.700 回答