When operating on files in Python, we generally need to first check whether the specified file or directory exists; otherwise, exceptions are likely to occur.

For example, we can useosmodule'sos.path.exists()method to check whether the file exists:

import os.path
os.path.isfile(fname)

If you want to determine whether it is a file or a directory, starting from Python 3.4 you can use the object-oriented method provided by the pathlib module (Python 2.7 uses the pathlib2 module):

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # 指定的文件存在

Check whether it is a directory:

if my_file.is_dir():
    # 指定的目录存在

If you want to check whether the path is a file or directory, you can use the exists() method:

if my_file.exists():
    # 指定的文件或目录存在

In a try statement block, you can use the resolve() method to determine:

try:
    my_abs_path = my_file.resolve()
except FileNotFoundError:
    # 不存在
else:
    # 存在