text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
If you use a context manager, the file is closed automatically for you
(如果使用上下文管理器,则将自动为您关闭文件)
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
If you're using Python2.6 or higher, it's preferred to use str.format()
(如果您使用的是Python2.6或更高版本,则最好使用str.format()
)
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
For python2.7 and higher you can use {}
instead of {0}
(对于python2.7及更高版本,您可以使用{}
代替{0}
)
In Python3, there is an optional file
parameter to the print
function
(在Python3中, print
功能有一个可选的file
参数)
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introduced f-strings for another alternative
(Python3.6引入了f字符串作为另一种选择)
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…