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 September 2025

1 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
$44.83 $55.00
Save 18%
Introduction to GIS Programming: A Practical Python Guide to Open Source Geospatial Tools
2 Learning Python: Powerful Object-Oriented Programming

Learning Python: Powerful Object-Oriented Programming

BUY & SAVE
$64.27 $79.99
Save 20%
Learning Python: Powerful Object-Oriented Programming
3 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
$40.77 $49.99
Save 18%
Python Tools for Scientists: An Introduction to Using Anaconda, JupyterLab, and Python's Scientific Libraries
4 Programming Computer Vision with Python: Tools and algorithms for analyzing images

Programming Computer Vision with Python: Tools and algorithms for analyzing images

BUY & SAVE
$28.99 $59.99
Save 52%
Programming Computer Vision with Python: Tools and algorithms for analyzing images
5 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

  • MASTER PYTHON INSTANTLY: QUICK REFERENCE FOR SYNTAX, DATA STRUCTURES, OOP.
  • ULTIMATE DESK MAT: LARGE, PREMIUM SIZE WITH NON-SLIP BASE, COLOR-CODED EASE.
  • ALL-IN-ONE PYTHON GUIDE: FROM BASICS TO ADVANCED, PERFECT FOR ALL CODERS.
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
6 Python Programming Language: a QuickStudy Laminated Reference Guide

Python Programming Language: a QuickStudy Laminated Reference Guide

BUY & SAVE
$8.95
Python Programming Language: a QuickStudy Laminated Reference Guide
7 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

  • TRACK ML PROJECTS END-TO-END WITH SCIKIT-LEARN FOR SEAMLESS WORKFLOW.
  • EXPLORE ADVANCED MODELS LIKE SVMS, DECISION TREES, AND RANDOM FORESTS.
  • BUILD NEURAL NETS FOR DIVERSE APPLICATIONS USING TENSORFLOW AND KERAS.
BUY & SAVE
$49.50 $89.99
Save 45%
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems
8 Python Data Science Handbook: Essential Tools for Working with Data

Python Data Science Handbook: Essential Tools for Working with Data

BUY & SAVE
$44.18 $79.99
Save 45%
Python Data Science Handbook: Essential Tools for Working with Data
+
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.