Fundamentals 3 min read

How to Check File and Directory Existence in Python with os and pathlib

This guide explains how to use Python's os module, the open function with exception handling, and the pathlib module to reliably determine whether files or directories exist, and how to handle missing‑file errors in a clean, cross‑platform way.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Check File and Directory Existence in Python with os and pathlib

Using the os module

Check if a file exists os.path.isfile(path) Check if a directory exists os.path.isdir(path) General existence check (file or directory)

# Using the path module
os.path.exists(path)
# Using access()
os.access(path, os.F_OK)

Using open and exception handling

If you call open() on a non‑existent file, Python raises an exception; you can catch it with a try block to determine existence.

When the file does not exist, open() raises FileNotFoundError. If the path points to a directory, it raises IsADirectoryError. If you lack permission, it raises PermissionError.

filePath = '/path/to/file'
try:
    file = open(filePath)
    file.close()
except FileNotFoundError:
    print("No such file or directory: '%s'" % filePath)
except IsADirectoryError:
    print("Is a directory: '%s'" % filePath)
except PermissionError:
    print("Permission denied: '%s'" % filePath)
else:
    print("File exists: '%s'" % filePath)

Using the pathlib module

import pathlib
path = pathlib.Path('path/to/file')
# Check if the path exists
path.exists()
# Check if it is a file
path.is_file()
# Check if it is a directory
path.is_dir()
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonException HandlingOS modulepathlibfile-handlingfile-existence
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.