Home > Article > Backend Development > How to determine if a file exists in Python
How Python determines whether a file exists: You can use the os.path.exists() method in the os module to determine, such as [if my_file.exists()]. Before starting the judgment, you need to execute the [import os.path] statement to import the os module.
When Python operates files, we generally need to first determine whether the specified file or directory exists, otherwise exceptions may easily occur.
For example, we can use the os.path.exists() method of os module to detect 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 is the pathlib2 module):
from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): # 指定的文件存在
Detect whether it is a directory:
if my_file.is_dir(): # 指定的目录存在
If you want to detect whether the path is a file or The directory can use the exists() method:
if my_file.exists(): # 指定的文件或目录存在
In the try statement block, you can use the resolve() method to determine:
try: my_abs_path = my_file.resolve()except FileNotFoundError: # 不存在else: # 存在
The above is the detailed content of How to determine if a file exists in Python. For more information, please follow other related articles on the PHP Chinese website!