强烈建议使用上下文管理器。作为一个优势,它确保文件始终处于关闭状态,无论如何:
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)