当文件是字符串格式的Python时,我如何打开文件并从文件中读取浮点数?我还想更改每个浮点数的值,并用新的值重写文件。
发布于 2012-06-15 23:09:48
假设每行有一个浮点数:
with open("myfile") as f:
floats = map(float, f)
# change floats
with open("myfile", "w") as f:
f.write("\n".join(map(str, floats)))
如果您想对格式进行更多的控制,请使用string的format
method。例如,这将在每个句点后仅打印3位数字:
f.write("\n".join(map("{0:.3f}".format, floats)))
发布于 2012-06-15 23:07:32
"float()“函数接受字符串作为输入,并将其转换为浮点数。
>>> float("123.456")
123.456
发布于 2012-06-15 23:09:07
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)
然后在你写完后写回它们
和一个较短的版本(未测试,从head编写)
with open("yourfile.txt") as input_file:
numbers = (float(number) for number in (line for line in (line.split() for line in input_file)))
https://stackoverflow.com/questions/11053318
复制相似问题