How to find if directory exists in Python? When working with files and directories in Python, you might need to know whether a directory exists or not. In this article, We will learn different methods to find if a directory exists or not in Python.
We will learn five different ways to check if a directory exists in Python. We will cover methods such as using the os.path.isdir()
and pathlib.Path.is_dir()
functions, as well as the os.access()
, os.stat()
, and os.path.exists()
functions. Let’s start with quick examples:
1. Quick Examples – Find if a Directory Exists
These examples are just a quick overview of the methods we will discuss in this article for checking if a directory exists. We will discuss them more in detail.
# Quick Examples
import os
import pathlib
import stat
# Directory path
dir_path = 'ParentDir/ChildDir'
# Using os.path.isdir() function
if os.path.isdir(dir_path):
print("Directory exists")
else:
print("Directory does not exist")
# Using pathlib.Path.is_dir() function
path_obj = pathlib.Path('directory path')
if path_obj.is_dir():
print("Directory exists")
else:
print("Directory does not exist")
# Using os.path.exists() function
if os.path.exists(dir_path):
if os.path.isdir(dir_path):
print("Directory exists")
else:
print("Path exists but is not a directory")
else:
print("Path does not exist")
2. os.path.isdir() Function – Find if Directory Exists
In Python, the os
module provides different utilities to interact with the operating system. One of them is the os.path
sub-module. It provides several functions for working with file and directory paths.
One of these functions is the isdir()
function, which checks if a given path exists and is a directory. If the path exists and is a directory, it returns True
, otherwise it returns False
.
The syntax of the os.path.isdir()
function:
# Syntax
os.path.isdir(path)
The path
argument is the path of the directory that we want to check. It can be an absolute or a relative path.
See the below example:
# os.path.isdir() Function
import os
# Replace the path with the directory path
path = 'directory-path'
# Check if the path is a direcoty
if os.path.isdir(path):
print("Directory exists")
else:
print("Directory does not exist")
# Output:
# Directory does not exist
The os.path.isdir()
function only checks if a directory exists, and not if the user has permissions to access it. If you need to check if the user has permission to access the directory, you can use the os.access()
function, which we’ll cover in the next section.
3. pathlib.Path.is_dir() – Check if Directory Exists
The pathlib
module is also providing an object-oriented way of working with file and directory paths. One of the methods available in the Path
class is the is_dir()
method, which checks if the given path exists and is a directory. If the path exists and is a directory, it returns True
, otherwise it returns False
.
See the below example:
# Using the pathlib module
from pathlib import Path
# The path variable contains the directory path
path = 'directory path'
if Path(path).is_dir():
print("Directory exists")
else:
print("Directory does not exist")
4. os.path.exists() – Find if Directory Exists
As mentioned earlier the sub-module os.path
in Python provides several functions. One another that we can use for this particular case is the exists()
function, which checks if a given path exists, regardless of whether it’s a file or a directory.
If the path exists, it returns True
, otherwise it returns False
.
Example of using the os.path.exists()
function to check if a directory exists:
# Using the os module
import os
path = 'directory path'
if os.path.exists(path) and os.path.isdir(path):
print("Directory exists")
else:
print("Directory does not exist")
5. os.access() – Check if Directory Exists
The access()
function, checks if the user has specified access to a given path. However we can use this into check if a directory exists or not using the mode
argument.
The syntax of the os.access()
:
os.access(path, mode)
The mode
argument is an integer that specifies the type of access that we want to check for. The possible values for mode
are:
os.F_OK
: to check if the path existsos.R_OK
: to check if the user has read permissionos.W_OK
: to check if the user has write permissionos.X_OK
: to check if the user has execute permission
See the below example:
# Using os.access() method
import os
path = 'directory path'
if os.access(path, os.R_OK):
print("User has read permission to directory")
else:
print("User does not have read permission to directory")
6. The os.stat() function
The stat()
function returns information about a file or directory specified by the path argument. The os.stat()
function is more powerful than just checking if a directory exists. It can provide information about the file size, creation time, modification time, and more.
# Using the os.stat() method
import os
import stat
path = 'directory path'
try:
mode = os.stat(path).st_mode
if stat.S_ISDIR(mode):
print("Directory exists")
else:
print("Directory does not exist")
except FileNotFoundError:
print("Directory does not exist")
7. Summary and Conclusion
In this article, we have learned how to find if a directory exists or not using different methods in python. I hope this article was helpful, if you have any questions, please ask them in the comment section.
Happy Coding!
Related Articles
- How to write a file in Python?
- Get filename without extension in Python?
- Python write JSON data to a file?
- How to move a file in Python?
- Why Python creates .pyc files when it is interpreted language?
- How to read a text file into a string and strip newlines?
- File Handling in Python
- How to Print to stderr in Python?
- How do you read from stdin in Python?
- How to Append to a File in Python?
- Extract extension from filename in Python.
- Different ways to Write Line to File in Python