将字符串打印到文本文件

新手上路,请多包涵

我正在使用 Python 打开一个文本文档:

 text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount')

text_file.close()

我想将字符串变量 TotalAmount 的值替换到文本文档中。有人可以让我知道该怎么做吗?

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

阅读 612
2 个回答

强烈建议使用上下文管理器。作为一个优势,确保文件始终关闭,无论如何:

 with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

这是显式版本(但请记住,上面的上下文管理器版本应该是首选):

 text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

如果你使用的是Python2.6或更高版本,最好使用 str.format()

 with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

对于 python2.7 及更高版本,您可以使用 {} 而不是 {0}

在 Python3 中,有一个可选的 file 参数到 print 函数

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6 为另一种选择引入了 f-strings

 with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)

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

如果你想传递多个参数,你可以使用元组

price = 33.3
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

更多: 在 python 中打印多个参数

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

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