擅长:python、mysql、java
<p>正如@Martjin已经说过的,你已经回答了你自己的问题。我只想对手册中的解释加以详细说明,以便更好地理解正文</p>
<p>“x”:打开进行独占创建,如果文件已存在则失败</p>
<p>当您指定<code>exclusive creation</code>时,这显然意味着您将使用此模式以独占方式创建文件。当您不会意外地使用<code>w</code>或<code>a</code>模式截断/追加现有文件时,就需要这样做。</p>
<p>如果没有这种情况,开发人员应该谨慎地检查文件的存在性,然后跳转到打开文件进行更新。</p>
<p>使用此模式,您的代码将简单地编写为</p>
<pre><code>try:
with open("fname", "x") as fout:
#Work with your open file
except FileExistsError:
# Your error handling goes here
</code></pre>
<p>以前你的代码可能是</p>
<pre><code>import os.path
if os.path.isfile(fname):
# Your error handling goes here
else:
with open("fname", "w") as fout:
# Work with your open file
</code></pre>