In Python, you can use the os
module or the pathlib
module to check if a file or directory exists. Below are examples of both methods:
Using os
module:
import os
# Check if a file exists
if os.path.isfile('path/to/file'):
print("File exists")
else:
print("File does not exist")
# Check if a directory exists
if os.path.isdir('path/to/directory'):
print("Directory exists")
else:
print("Directory does not exist")
Using pathlib
module (recommended for modern Python code):
from pathlib import Path
# Check if a file exists
file_path = Path('path/to/file')
if file_path.is_file():
print("File exists")
else:
print("File does not exist")
# Check if a directory exists
directory_path = Path('path/to/directory')
if directory_path.is_dir():
print("Directory exists")
else:
print("Directory does not exist")
The pathlib
module is generally considered more flexible and easier to use for path-related tasks, so it’s often preferred in newer code.