Python打印字符串到文本文件 [英] Python Print String To Text File
问题描述
$ b
text_file = open(Output.txt,w)使用Python打开文本文档)
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()
如果你使用一个上下文管理器,文件会自动关闭给你
<$ c
text_file.write(Purchase Amount:%s%TotalAmount)
pre>
如果您使用Python2.6或更高版本,则最好使用
str.format()
以open(Output.txt,w)作为文本文件:
text_file.write(Purchase Amount :{0}。format(TotalAmount))
对于python2.7及更高版本, code $ {code $ {$ c $ {$ c $ {$ c $ {$ c $ {$ c $ {$ c $}}}在Python3中,对于
文件
参数
打开(Output.tx (Purchase Amount:{}。format(TotalAmount),file = text_file)
Python3.6引入了 f-字符串为另一个替代方案
with open(Output.txt,w )as text_file:
print(fPurchase Amount:{TotalAmount},file = text_file)
I'm using Python to open a text document:
text_file = open("Output.txt", "w") text_file.write("Purchase Amount: " 'TotalAmount') text_file.close()
I want to enter the string called "TotalAmount" into the text document. Can someone please let me know how to do this?
解决方案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()
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}
In Python3, there is an optional
file
parameter to thewith open("Output.txt", "w") as text_file: print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introduced f-strings for another alternative
with open("Output.txt", "w") as text_file: print(f"Purchase Amount: {TotalAmount}", file=text_file)
这篇关于Python打印字符串到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!