擅长:python、mysql、java
<pre><code>text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
</code></pre>
<p>如果使用上下文管理器,文件将自动为您关闭</p>
<pre><code>with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
</code></pre>
<p>如果您使用Python2.6或更高版本,最好使用<code>str.format()</code></p>
<pre><code>with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
</code></pre>
<p>对于python2.7及更高版本,可以使用<code>{}</code>,而不是<code>{0}</code></p>
<p>在Python3中,<code>print</code>函数有一个可选的<code>file</code>参数</p>
<pre><code>with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
</code></pre>
<p>Python3.6引入了<a href="https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals" rel="noreferrer">f-strings</a>作为另一种选择</p>
<pre><code>with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
</code></pre>