我正在使用 Python 打开一个文本文档:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
我想将字符串变量 TotalAmount
的值替换到文本文档中。有人可以告诉我该怎么做吗?
最佳答案
强烈建议使用上下文管理器。作为一个优势,它确保文件始终处于关闭状态,无论如何:
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中,print
函数有一个可选的file
参数
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)
关于python - 将字符串打印到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5214578/