Question

Check Whether a Directory Exists in Python

pythondirectory

Question

How can I check whether a directory exists in Python?

Short Answer

You will learn how to distinguish an existing directory from a file or missing path in Python. You will use the modern pathlib approach, understand the older os.path alternative, and apply safe checks before reading or creating folders.

Concept

A filesystem path can point to several different things:

  • A directory (folder)
  • A file
  • A symbolic link
  • Nothing, because the path does not exist

To check specifically for a directory, use a directory-aware method rather than only checking whether the path exists.

In modern Python, pathlib.Path.is_dir() is the clearest choice. It returns True only when the path exists and is a directory.

from pathlib import Path

reports = Path("reports")

if reports.is_dir():
    print("The reports directory exists.")
else:
    print("The reports directory does not exist.")

This matters because a path named reports could exist as a regular file. A general existence check would not tell you whether it is safe to use that path as a folder.

Mental Model

Think of a path as an address.

  • path.exists() asks: “Is there anything at this address?”
  • path.is_file() asks: “Is there a file at this address?”
  • path.is_dir() asks: “Is there a folder at this address?”

If your code needs to store several files inside an address, you need a folder, so is_dir() asks the precise question.

Take Quiz

Syntax and Examples

Use Path.is_dir() from the built-in pathlib module.

from pathlib import Path

folder = Path("data/uploads")

if folder.is_dir():
    print(f"{folder} is an existing directory")
else:
    print(f"{folder} is missing or is not a directory")

Path("data/uploads") creates a path object. It does not create the folder. Calling folder.is_dir() checks the filesystem and returns a Boolean value.

You can also use an absolute path:

from pathlib import Path

folder = Path("/var/app/uploads")
print(folder.is_dir())

Older os.path syntax

Many existing projects use os.path.isdir():

import os

if os.path.isdir("data/uploads"):
    print("Directory exists")

It is valid, but pathlib is usually easier to read and compose, especially when joining paths with /.

Step by Step Execution

Consider this code:

from pathlib import Path

export_dir = Path("exports")

if not export_dir.is_dir():
    export_dir.mkdir(parents=True)

print("Ready to save files in", export_dir)

Step by step:

  1. Path("exports") represents a path named exports relative to the current working directory.
  2. export_dir.is_dir() checks whether that path currently exists as a directory.
  3. not reverses the result. If the directory is absent, the condition is True.
  4. mkdir(parents=True) creates exports. parents=True also creates missing parent directories if needed.
  5. The final print runs whether the directory already existed or was just created.

For repeated or concurrent setup code, prefer this shorter creation pattern:

export_dir.mkdir(parents=True, exist_ok=True)

It creates the directory when needed and does not fail merely because the directory already exists.

Real World Use Cases

Directory checks are useful whenever code depends on local storage:

  • File uploads: Verify that an upload folder is available before saving user files.
  • Reports and exports: Create or validate a reports/ directory before writing CSV, PDF, or JSON output.
  • Application configuration: Check whether a configuration directory exists before loading settings files.
  • Data pipelines: Confirm that an input folder exists before scanning it for source files.
  • Backups: Ensure a backup destination is a directory before copying data.
  • Command-line tools: Give a clear error when a user supplies a path that does not point to a folder.
Take Quiz

Real Codebase Usage

In production code, developers often validate a path early and produce a useful error message.

Guard clause for required input

from pathlib import Path

def load_csv_files(input_dir: str) -> list[Path]:
    folder = Path(input_dir)

    if not folder.is_dir():
        raise ValueError(f"Input directory does not exist: {folder}")

    return list(folder.glob("*.csv"))

The guard clause prevents the rest of the function from running with an invalid directory.

Ensure an output directory exists

from pathlib import Path

def save_report(content: str) -> Path:
    output_dir = Path("output")
    output_dir.mkdir(parents=True, exist_ok=True)

    report_path = output_dir / "report.txt"
    report_path.write_text(content, encoding="utf-8")
    return report_path

For output locations your program owns, creating the directory is often more useful than checking first. exist_ok=True handles the normal “already exists” case.

Important filesystem caveat

A path can change after you check it. For example, another process can delete a directory between is_dir() and a later file operation. Therefore, check for clearer control flow, but still handle OSError around the operation that must succeed.

Common Mistakes

Using exists() when a directory is required

This code accepts both files and directories:

from pathlib import Path

path = Path("settings")
if path.exists():
    print("Ready")

If settings is a file, printing “Ready” may be incorrect. Use is_dir() when your code requires a folder.

if path.is_dir():
    print("Ready")

Comparing a method instead of calling it

Broken code:

from pathlib import Path

folder = Path("data")
if folder.is_dir:
    print("Directory exists")

folder.is_dir is the method itself, which is truthy. Call it with parentheses:

if folder.is_dir():
    print("Directory exists")

Assuming Path() creates the directory

from pathlib import Path

folder = Path("new_folder")

This only creates a Python object representing a location. To create the folder, call:

folder.mkdir()

Forgetting parent directories

This can fail if data/ does not exist:

from pathlib import Path

Path("data/output").mkdir()

Use parents=True when missing parent folders should be created:

Path("data/output").mkdir(parents=True, exist_ok=True)

Relying on a check instead of handling errors

Permission changes, deleted folders, and network-drive failures can occur after a successful check. Wrap important reads or writes in try/except OSError when your program needs robust error handling.

Comparisons

CheckReturns True whenBest use
Path(path).exists()A file, directory, or other filesystem entry existsYou only need to know whether anything exists there
Path(path).is_dir()The path exists and is a directoryYou need a folder
Path(path).is_file()The path exists and is a regular fileYou need a file
os.path.exists(path)Any filesystem entry existsMaintaining older os.path code
os.path.isdir(path)The path exists and is a directoryMaintaining older os.path code

pathlib versus os.path

StyleExampleNotes
pathlibPath("data") / "users.json"Modern, object-oriented, and readable
os.pathos.path.join("data", "users.json")Older but still supported and common

Both work. Avoid mixing styles unnecessarily within the same piece of code.

Take Quiz

Cheat Sheet

from pathlib import Path

folder = Path("data")

folder.exists()                     # True for a file or directory
folder.is_dir()                     # True only for an existing directory
folder.is_file()                    # True only for an existing file
folder.mkdir()                      # Create one directory
folder.mkdir(parents=True)          # Also create missing parent directories
folder.mkdir(parents=True, exist_ok=True)  # Create if absent; no error if present
import os

os.path.exists("data")  # File or directory exists
os.path.isdir("data")   # Directory exists
os.path.isfile("x.txt") # File exists

Rules:

  • Prefer Path.is_dir() when you specifically require a directory.
  • A Path object does not create anything until you call an operation such as mkdir().
  • Use exist_ok=True when creating a directory that may already exist.
  • Handle OSError for operations where permissions or filesystem changes matter.

FAQ

Does Path.is_dir() return False if the folder does not exist?

Yes. It returns False when the path is missing and when the path exists but is not a directory.

Does Path.exists() check whether a path is a directory?

No. It returns True for both files and directories. Use is_dir() to require a directory.

What is the recommended way to check for a directory in Python?

Use Path(path).is_dir() from pathlib in new code. It is clear and works across supported operating systems.

How do I create a directory only if it does not exist?

Use Path("folder").mkdir(parents=True, exist_ok=True). It creates missing directories and does not raise an error if the target directory already exists.

Is os.path.isdir() still valid in Python?

Yes. It is fully valid and is common in older codebases. pathlib is generally preferred for new code because its path operations are easier to read.

Can a directory check fail because of permissions?

It can. Filesystem access may be affected by permissions, unavailable drives, or other operating-system errors. Handle OSError around critical filesystem operations.

Does is_dir() work with relative paths?

Yes. Relative paths are resolved from the program's current working directory.

Take Quiz

Mini Project

Description

Build a small report-saving utility. It accepts a report name and text, makes sure an output directory is available, and saves the text as a .txt file. This reflects a common task in scripts that generate logs, exports, or reports.

Goal

Create an output directory when necessary and save a report file inside it.

Requirements

Use pathlib.Path for all path operations. Ensure an output directory exists before writing the file. Save a report as daily_report.txt. Print the path of the saved report. Read the saved file and print its contents.

Take Quiz

Keep learning

Related questions

View more