如何读取文件中的花车? [英] How to read in floats from a file?
本文介绍了如何读取文件中的花车?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python中打开一个文件并从文件中读取文件中的字符串格式?我也想改变每个浮动的值,并用新值重写文件。
解决方案
假设有一个每行浮点数:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
更改浮动
以open(myfile,w)作为f:
f.write(\\\
.join(map (str,float)))
如果您想更多地使用格式化,请使用 format
方法的字符串。例如,这将只在每个时间段后打印3位:
f.write(\\\
.join(map ({0:.3f}。format,float)))
How can I open a file and read in the floats from the file, when it is in string format, in Python? I would also like to change the values of the each float and rewrite the file over with the new values.
解决方案
Assuming there's one float per line:
with open("myfile") as f:
floats = map(float, f)
# change floats
with open("myfile", "w") as f:
f.write("\n".join(map(str, floats)))
If you want more control with formatting, use the format
method of string. For instance, this will only print 3 digits after each period:
f.write("\n".join(map("{0:.3f}".format, floats)))
这篇关于如何读取文件中的花车?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文