Pet*_*nes 5 python string floating-point file
如何以文件串格式在Python中打开文件并从文件中读取浮点数?我还想更改每个浮点数的值,并使用新值重写文件.
Lau*_*low 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)))
Run Code Online (Sandbox Code Playgroud)
如果您想要更多格式化控件,请使用string format方法.例如,每个期间后只会打印3位数字:
f.write("\n".join(map("{0:.3f}".format, floats)))
Run Code Online (Sandbox Code Playgroud)
“float()”函数接受字符串作为输入并将其转换为浮点数。
>>> float("123.456")
123.456
Run Code Online (Sandbox Code Playgroud)