<p>如果您检查的原因是为了执行类似<code>if file_exists: open_it()</code>的操作,则在尝试打开它时使用<code>try</code>会更安全。检查然后打开可能会导致文件被删除或移动,或者在您检查文件和尝试打开文件之间发生某些情况。</p>
<p>如果不打算立即打开文件,可以使用<a href="https://docs.python.org/library/os.path.html#os.path.isfile" rel="noreferrer">^{<cd3>}</a></p>
<blockquote>
<p>Return <code>True</code> if path is an existing regular file. This follows symbolic links, so both <a href="https://docs.python.org/library/os.path.html#os.path.islink" rel="noreferrer">islink()</a> and <a href="https://docs.python.org/library/os.path.html#os.path.isfile" rel="noreferrer">isfile()</a> can be true for the same path.</p>
</blockquote>
<pre><code>import os.path
os.path.isfile(fname)
</code></pre>
<p>如果你需要确定它是一个文件。</p>
<p>从Python 3.4开始,<a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file" rel="noreferrer">^{<cd4>} module</a>提供了一种面向对象的方法(在Python 2.7中被移植到<code>pathlib2</code>):</p>
<pre><code>from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
</code></pre>
<p>要检查目录,请执行以下操作:</p>
<pre><code>if my_file.is_dir():
# directory exists
</code></pre>
<p>要检查<code>Path</code>对象是否独立于文件或目录而存在,请使用<code>exists()</code>:</p>
<pre><code>if my_file.exists():
# path exists
</code></pre>
<p>也可以在<code>try</code>块中使用<code>resolve(strict=True)</code>:</p>
<pre><code>try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
</code></pre>