强烈建议使用上下文管理器。一个优点是,无论发生什么情况,都可以确保文件始终关闭:
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 弦另一种选择
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)