python - 在 Python 中将浮点值写入文件的正确格式是什么

标签 python python-3.x python-3.6

我有一堆浮点值,例如:

x1 = 1.11111111

x2 = 2.22222222

我想将这些值写入文件:

f = open("a.dat", "w+")
f.write("This is x1: ",x1)
f.write("\n")              #I want to separate the 2 lines
f.write("This is x2: ",x2)

此时我在第二行得到一个错误:

write() takes exactly one argument (2 given)

如何写入文件,以便在打开文件时看到以下格式:

This is x1: 1,1111111
This is x2: 2,2222222

是的,文件必须是 ***.dat

这不是.txt

最佳答案

write 函数采用单个字符串。您正在尝试像 print 那样使用它,它接受任意数量的参数。


事实上,您可以只使用 print 。默认情况下,它的输出只会转到程序的输出 ( stdout ),通过向它传递一个 file 参数,您可以将它发送到一个文本文件:

print("This is x1: ", x1, file=f)

如果您想使用write,您需要将输出格式化为单个字符串。最简单的方法是使用 f 字符串:

f.write(f"This is x1: {x1}\n")

请注意,我必须在末尾包含一个 \nprint 函数将其 end 参数添加到它打印的内容的末尾,默认为 \nwrite 方法没有。


既是为了向后兼容,也是因为有时它们更方便,Python 有其他方法可以做同样的事情,包括显式 string formatting :

f.write("This is x1: {}\n".format(x1))

... printf-style formatting :

f.write("This is x1: %s\n" % (x1,))

... template strings :

f.write(string.Template("This is $x1\n").substitute(x1=x1))

…和字符串连接:

f.write("This is x1: " + str(x1) + "\n")

除了最后一个以外,所有这些都会自动将 x1 转换为字符串,其方式与 str(x1) 相同,但也允许其他选项,例如:

f.write(f"This is {x1:.8f}\n")

这会将 x1 转换为 float,然后以 8 位精度对其进行格式化。因此,除了打印出带有 8 位小数的 1.111111112.22222222 之外,它还会将 1.1 打印为 1.100000001.23456789012345 作为 1.23456789

相同的格式字符串适用于 f 字符串、str.formatformat 函数:

print("This is x1: ", format(x1, '.8f'), file=f)
f.write("This is x1: {:.8f}\n".format(x1))
f.write("This is x1: " + format(x1, '.8f') + "\n")

…和其他两种方法有相似但不那么强大的格式化语言:

f.write("This is x1: %.8f\n" % (x1,))

关于python - 在 Python 中将浮点值写入文件的正确格式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50893146/

相关文章:

python - 在 Python 3.x 中更改 Active Directory 用户密码

python - django 分页不适用于 django 过滤器

file - 使用Python 3.6解析、编辑和保存dhcpd.conf文件

python - 将 QHBoxLayout 的每个小部件对齐到顶部

python - 如何在python中正确处理多个二进制文件?

python - 路径函数在 python IDLE 和 google colab 中的工作方式是否不同?

python - odoo 12. 我无法对 Many2one 字段进行动态过滤

python - 追加在程序中多次调用时会返回语法错误

python - 如何在Python文件中运行多个Linux命令

python - featuretools历史标签计数