How to check whether a file exists without exceptions in Python?

In Python, you can check if a file exists without raising exceptions using the os.path module or the modern pathlib library. These methods return a boolean (True/False) and do not throw errors if the file is missing.

Method 1: Using os.path (Legacy Approach)

import os

file_path = "path/to/your/file.txt"

# Check if the file exists
if os.path.exists(file_path) and os.path.isfile(file_path):
    print("File exists!")
else:
    print("File does not exist.")

Explanation:

  • os.path.exists(path): Returns True if the path exists (file or directory).
  • os.path.isfile(path): Returns True only if the path points to a file (not a directory).

Method 2: Using pathlib (Modern, Python 3.4+)

from pathlib import Path

file_path = Path("path/to/your/file.txt")

# Check if the file exists
if file_path.exists() and file_path.is_file():
    print("File exists!")
else:
    print("File does not exist.")

Explanation:

  • Path.exists(): Returns True if the path exists.
  • Path.is_file(): Returns True only if the path points to a file.

Key Notes:

  1. No Exceptions Raised: Both methods return True/False and do not raise FileNotFoundError or other exceptions.
  2. Race Conditions: Even if the check passes, the file could be deleted/modified before you open it. Always handle errors when opening files.
  3. Directories vs. Files: Use os.path.isdir() or Path.is_dir() if you need to check for directories.

Alternatives (Avoid for Simple Checks):

  • Using tryexcept (raises exceptions but handles edge cases better):
  try:
      with open(file_path, "r") as f:
          print("File exists and is readable!")
  except FileNotFoundError:
      print("File does not exist.")
  except PermissionError:
      print("No read permissions.")


Use this if you plan to immediately use the file, as it avoids race conditions.

Summary:

MethodCode ExampleProsCons
os.pathos.path.exists() + os.path.isfile()Simple, works in all Python versionsLess modern
pathlibPath.exists() + Path.is_file()Object-oriented, cleaner syntaxRequires Python ≥3.4
tryexceptHandle FileNotFoundErrorRobust against race conditionsInvolves exceptions

Use os.path or pathlib for simple checks, and tryexcept if you need to open the file afterward.

Leave a Reply

Your email address will not be published. Required fields are marked *