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

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

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

text_file.close()

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

最佳答案

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

如果使用上下文管理器,则将自动为您关闭文件
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

如果您使用的是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)

10-08 12:59