Python provides straightforward approaches via standard libraries. These methods are concise and help you to write clean and exception-free code.
Method 1: Using os.path.exists()
This method works across operating systems and returns True if the file (or directory) exists.
python
import os
file_path = “example.txt”
if os.path.exists(file_path):
print(“File exists.”)
else:
print(“File does not exist.”)
Works for both files and directories. Use os.path.isfile() to check specifically for files.
Method 2: Using pathlib.Path.exists()
Introduced in python 3.4, It’s a more modern, object-oriented way to work with file paths.
python
from pathlib import Path
file = Path(“example.txt”)
if file.exists():
print(“File exists.”)
else:
print(“File does not exist.”)
Pathlib is preferred for newer codebases due to its clean syntax and better path handling.
Also Read:
Tip
- To check only for files (not directories) use os.path.isfile() or file.is_file() in pathlib.
- Avoid using try-except just to test file presence; these methods are faster and more readable.