Home >Backend Development >Python Tutorial >How Can I Check for File Existence in Python Without Using Exceptions?
Question:
How can I determine if a file exists without resorting to exception handling?
Answer:
try-except Approach:
While using a try-except block to check for file existence may seem intuitive, it introduces a safety risk. Suppose you plan to open the file after checking. In that case, there's a chance the file could be deleted or modified between the check and open operations.
os.path.isfile:
For cases where immediate file opening is not necessary, you can leverage os.path.isfile. This function evaluates if the specified path points to an existing file, including those accessed through symbolic links.
import os.path os.path.isfile(fname)
pathlib Approach (Python 3.4 ):
Python 3.4 introduced pathlib for an object-oriented file system interaction approach.
To check for file existence:
from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): # file exists
For directories:
if my_file.is_dir(): # directory exists
To verify the existence of a path regardless of file type:
if my_file.exists(): # path exists
Additionally, you can use resolve(strict=True) within a try block for a more precise check:
try: my_abs_path = my_file.resolve(strict=True) except FileNotFoundError: # doesn't exist else: # exists
The above is the detailed content of How Can I Check for File Existence in Python Without Using Exceptions?. For more information, please follow other related articles on the PHP Chinese website!