Skip to main content
St Louis

Back to all posts

How to Check If A Directory Exists In Python?

Published on
4 min read
How to Check If A Directory Exists In Python? image

Best Python Programming Tools to Buy in November 2025

1 Python Programming Cheat Sheet Desk Mat - Large Mouse Pad with Complete Code Reference (31.5" x 11.8") - Professional Coding Guide Mousepad for Beginners & Software Engineers

Python Programming Cheat Sheet Desk Mat - Large Mouse Pad with Complete Code Reference (31.5" x 11.8") - Professional Coding Guide Mousepad for Beginners & Software Engineers

  • COMPREHENSIVE PYTHON SYNTAX & OOP CONCEPTS FOR QUICK CODING REFERENCE.
  • LARGE, NON-SLIP DESK MAT FOR STABILITY DURING INTENSE CODING SESSIONS.
  • BOOST PRODUCTIVITY WITH INSTANT ACCESS TO ESSENTIAL PYTHON COMMANDS.
BUY & SAVE
$25.95
Python Programming Cheat Sheet Desk Mat - Large Mouse Pad with Complete Code Reference (31.5" x 11.8") - Professional Coding Guide Mousepad for Beginners & Software Engineers
2 Python Programming Logo for Programmers T-Shirt

Python Programming Logo for Programmers T-Shirt

  • VINTAGE PYTHON DESIGN FOR PASSIONATE DEVELOPERS AND ENGINEERS!
  • LIGHTWEIGHT AND CLASSIC FIT FOR ALL-DAY COMFORT WHILE CODING.
  • DURABLE DOUBLE-NEEDLE STITCHING ENSURES LONG-LASTING WEAR.
BUY & SAVE
$19.99
Python Programming Logo for Programmers T-Shirt
3 Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems

Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems

  • MASTER END-TO-END ML PROJECTS WITH SCIKIT-LEARN INSIGHTS.
  • EXPLORE DIVERSE MODELS: SVMS, TREES, FORESTS, AND ENSEMBLES.
  • BUILD ADVANCED NEURAL NETS USING TENSORFLOW AND KERAS TOOLS.
BUY & SAVE
$46.95 $89.99
Save 48%
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems
4 Software Design by Example

Software Design by Example

BUY & SAVE
$51.19 $63.99
Save 20%
Software Design by Example
5 Python Tools for Scientists: An Introduction to Using Anaconda, JupyterLab, and Python's Scientific Libraries

Python Tools for Scientists: An Introduction to Using Anaconda, JupyterLab, and Python's Scientific Libraries

BUY & SAVE
$38.67 $49.99
Save 23%
Python Tools for Scientists: An Introduction to Using Anaconda, JupyterLab, and Python's Scientific Libraries
6 Learning Python: Powerful Object-Oriented Programming

Learning Python: Powerful Object-Oriented Programming

BUY & SAVE
$55.68 $79.99
Save 30%
Learning Python: Powerful Object-Oriented Programming
7 Introduction to GIS Programming: A Practical Python Guide to Open Source Geospatial Tools

Introduction to GIS Programming: A Practical Python Guide to Open Source Geospatial Tools

BUY & SAVE
$48.48 $55.00
Save 12%
Introduction to GIS Programming: A Practical Python Guide to Open Source Geospatial Tools
+
ONE MORE?

To check if a directory exists in Python, you can use the os.path.exists() or os.path.isdir() function from the os module. Here's how you can do it:

  1. Import the os module:

import os

  1. Specify the path of the directory you want to check in a variable:

dir_path = "/path/to/directory"

  1. Use the os.path.exists() function to check if the directory exists. This function returns True if the directory exists, or False otherwise:

if os.path.exists(dir_path): print("Directory exists!") else: print("Directory does not exist!")

Alternatively, you can use the os.path.isdir() function to specifically check if the path points to a directory:

if os.path.isdir(dir_path): print("Directory exists!") else: print("Directory does not exist!")

Using either of these methods, you can determine whether a directory exists in Python.

How to extract only the filename from a directory path in Python?

To extract only the filename from a directory path in Python, you can make use of the os.path module. Here's an example:

import os

path = '/path/to/directory/filename.ext' filename = os.path.basename(path) print(filename)

Output:

filename.ext

In the above example, the os.path.basename() function is used to extract the filename from the given path.

How to check if a specific directory exists in Python?

To check if a specific directory exists in Python, you can use the os.path.exists() function along with the os.path.isdir() function.

Here's an example:

import os

directory = "path/to/directory"

if os.path.exists(directory) and os.path.isdir(directory): print("Directory exists") else: print("Directory does not exist")

In this example, replace "path/to/directory" with the actual path of the directory you want to check. The os.path.exists() function checks if the path exists, and the os.path.isdir() function checks if the path leads to a directory.

How to check if a directory is empty in Python?

You can use the os.listdir() function to check if a directory is empty in Python. Here is an example that demonstrates how to do this:

import os

def is_directory_empty(directory_path): if not os.path.isdir(directory_path): raise ValueError(f"{directory_path} is not a valid directory")

return len(os.listdir(directory\_path)) == 0

Example usage

directory = "/path/to/directory" if is_directory_empty(directory): print(f"The directory {directory} is empty") else: print(f"The directory {directory} is not empty")

In this example, the is_directory_empty() function checks if the provided path is a valid directory using os.path.isdir(). It then retrieves the list of files and directories in the given directory using os.listdir(). If the length of the returned list is 0, it means that the directory is empty and the function returns True. Otherwise, it returns False.

How to exclude hidden files from a directory listing in Python?

To exclude hidden files from a directory listing in Python, you can utilize the os module along with list comprehension.

Here's an example that demonstrates how to achieve this:

import os

def list_directory_files(directory): files = [file for file in os.listdir(directory) if not file.startswith('.')] return files

Specify the directory path

directory_path = '/path/to/directory'

Get the list of non-hidden files in the directory

files_list = list_directory_files(directory_path)

Print the list of files excluding hidden files

for file in files_list: print(file)

In this example, the list_directory_files function takes a directory path as input and returns a list of files within the directory, excluding the hidden files. The os.listdir function retrieves all files and directories within the specified directory. Then, list comprehension is used to filter out the files that start with a period (indicating hidden files) using the str.startswith method. Finally, the resulting list is returned.

You can replace '/path/to/directory' with the actual directory path you want to list the files from.

How to filter files by extension in a directory in Python?

To filter files by extension in a directory in Python, you can use the glob module. Here's a code example:

import glob

directory = '/path/to/directory' extension = '.txt'

files = glob.glob(directory + '/*' + extension)

In this example, directory is the path to the directory you want to search in, and extension is the file extension you want to filter for (e.g., ".txt" for text files, ".csv" for CSV files, etc.).

The glob.glob() function returns a list of filenames matching the specified pattern. The pattern here is formed by concatenating the directory path with /* (to match any filename in the directory) and then adding the extension you want to filter for.