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

新手上路,请多包涵

我有一堆浮点值,例如:

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

原文由 Tamamo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 818
2 个回答

您写入文件的方式看起来像是给 write 函数提供了两个参数。所以你只需要传递一个参数。尝试将 x1 和 x2 转换为字符串,然后写入文件。

 f.write("This is x1 " + str(x1))
f.write("This is x2 " + str(x2))

原文由 Bibek Bhandari 发布,翻译遵循 CC BY-SA 4.0 许可协议

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


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

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


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

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

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


既为了向后兼容,也因为偶尔它们更方便,Python 有其他方法来做同样的事情,包括显式 字符串格式化

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

printf 样式格式

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

模板字符串

 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 位精度对其进行格式化。 So, in addition to printing out 1.11111111 and 2.22222222 with 8 decimals, it’ll also print 1.1 as 1.10000000 and 1.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,))

原文由 abarnert 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题