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中,打印函数有一个可选的文件参数
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)