0
0
PythonHow-ToBeginner · 3 min read

How to Check if Path Exists in Python: Simple Guide

In Python, you can check if a path exists using pathlib.Path.exists() or os.path.exists(). Both return True if the path exists and False if it does not.
📐

Syntax

There are two common ways to check if a path exists in Python:

  • Using pathlib: Create a Path object and call exists().
  • Using os.path: Call os.path.exists() with the path as a string.

Both methods return a boolean indicating if the path exists.

python
from pathlib import Path
import os

# Using pathlib
path = Path('some/path')
path.exists()  # Returns True if path exists, else False

# Using os.path
os.path.exists('some/path')  # Returns True if path exists, else False
💻

Example

This example shows how to check if a file or directory exists using both pathlib and os.path. It prints messages based on the result.

python
from pathlib import Path
import os

file_path = 'example.txt'

# Using pathlib
path = Path(file_path)
if path.exists():
    print(f"Path '{file_path}' exists (pathlib).")
else:
    print(f"Path '{file_path}' does not exist (pathlib).")

# Using os.path
if os.path.exists(file_path):
    print(f"Path '{file_path}' exists (os.path).")
else:
    print(f"Path '{file_path}' does not exist (os.path).")
Output
Path 'example.txt' does not exist (pathlib). Path 'example.txt' does not exist (os.path).
⚠️

Common Pitfalls

Some common mistakes when checking if a path exists:

  • Using a relative path without knowing the current working directory can cause unexpected results.
  • Confusing exists() with checking if the path is a file or directory. Use is_file() or is_dir() for that.
  • Not handling exceptions when the path string is invalid or inaccessible.
python
from pathlib import Path

path = Path('some/path')

# Wrong: assuming path exists without checking
# This may cause errors later if path is missing

# Right: check before using
if path.exists():
    print('Path exists, safe to use.')
else:
    print('Path does not exist, handle accordingly.')
📊

Quick Reference

MethodUsageReturns
pathlib.Path.exists()Path('your/path').exists()True if path exists, else False
os.path.exists()os.path.exists('your/path')True if path exists, else False
pathlib.Path.is_file()Path('your/path').is_file()True if path is a file
pathlib.Path.is_dir()Path('your/path').is_dir()True if path is a directory

Key Takeaways

Use pathlib.Path.exists() or os.path.exists() to check if a path exists in Python.
pathlib is modern and recommended for new code over os.path.
Check if a path is a file or directory with is_file() or is_dir() methods.
Always consider the current working directory when using relative paths.
Handle cases where the path might not exist to avoid errors.