How do I check if a directory exists in Python?

What’s the best way to check if a folder exists using Python? I’m trying to perform a conditional operation only if a specific directory is present.

Looking for a clean and reliable method to check if a directory exists using built-in modules.

For me, the most straightforward way is using os.path.isdir(). It’s part of the standard os module and works great across platforms.

Here’s a quick example:


import os

if os.path.isdir('/path/to/folder'):
    print("Directory exists!")
else:
    print("Nope.")

I use it in automation scripts where I need to avoid overwriting things or conditionally create folders.

I’ve switched to using pathlib.Path since Python 3.6+. It feels more modern and is object-oriented, which I really like:


from pathlib import Path

if Path('/some/dir').is_dir():
    print("Found it.")

It’s especially handy when chaining path operations—makes the code much easier to read.

I always check if a directory exists before trying to write files into it, and if not, I create it:

import os

if not os.path.exists('output'):
    os.makedirs('output')

This avoids errors and keeps everything tidy. Whether you use os.path.isdir() or pathlib, both are solid depending on your coding style.