如果您检查的原因是这样您可以执行类似的操作if file_exists: open_it()
,使用更安全try
围绕尝试打开它。检查然后打开文件的风险是,在检查和尝试打开文件之间,文件会被删除或移动或发生其他情况。
如果您不打算立即打开文件,可以使用os.path.isfile https://docs.python.org/library/os.path.html#os.path.isfile
Return True
如果路径是现有的常规文件。这遵循符号链接,因此两者islink() https://docs.python.org/library/os.path.html#os.path.islink and isfile() https://docs.python.org/library/os.path.html#os.path.isfile对于相同的路径可以是正确的。
import os.path
os.path.isfile(fname)
如果您需要确定它是一个文件。
从 Python 3.4 开始,pathlib module https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file提供面向对象的方法(向后移植到pathlib2
在 Python 2.7 中):
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
要检查目录,请执行以下操作:
if my_file.is_dir():
# directory exists
检查是否有Path
对象独立存在,无论是文件还是目录,使用exists()
:
if my_file.exists():
# path exists
您还可以使用resolve(strict=True)
in a try
block:
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists