Delete an Empty Directory in Python
In Python, you can delete an empty directory using the os.rmdir()
or pathlib.Path.rmdir()
method. These methods ensure that the directory is removed only if it is empty; otherwise, an error will occur.
Examples to Delete an Empty Directory
1. Using os.rmdir()
to Delete an Empty Directory
In this example, we will delete an empty directory empty_folder
using the os.rmdir()
method.
main.py
import os
# Define the directory name
dir_name = "empty_folder"
# Remove the empty directory
os.rmdir(dir_name)
print(f"Directory '{dir_name}' deleted successfully.")
Explanation:
- We import the
os
module, which provides functions for interacting with the operating system. - The variable
dir_name
stores the name of the directory we want to delete. - We use
os.rmdir(dir_name)
to delete the empty directory. - The program prints a confirmation message after the directory is deleted.
Output:
Directory 'empty_folder' deleted successfully.
2. Using pathlib.Path.rmdir()
to Delete an Empty Directory
In this example, we will use the pathlib
module, which provides an object-oriented approach to handling files and directories.
main.py
from pathlib import Path
# Define the directory path
dir_path = Path("empty_folder")
# Remove the empty directory
dir_path.rmdir()
print(f"Directory '{dir_path}' deleted successfully.")
Explanation:
- We import
Path
from thepathlib
module. - The variable
dir_path
stores the directory path as aPath
object. - We delete the directory using
dir_path.rmdir()
. - The program prints a confirmation message once the directory is deleted.
Output:
Directory 'empty_folder' deleted successfully.
3. Handling Errors When Deleting a Non-Empty Directory
In this example, we attempt to delete a non-empty directory non_empty_folder
to see how Python handles such cases. Replace the non_empty_folder
with the directory name of yours.
main.py
import os
# Define the directory name
dir_name = "non_empty_folder"
# Attempt to delete the directory
try:
os.rmdir(dir_name)
print(f"Directory '{dir_name}' deleted successfully.")
except OSError as e:
print(f"Error: {e}")
Explanation:
- We define
dir_name
as “non_empty_folder”. - We attempt to delete the directory using
os.rmdir()
. - Since the directory is not empty, an
OSError
is raised, which we catch and print the error message.
Output:
Error: [Errno 66] Directory not empty: 'non_empty_folder'
Conclusion
In this tutorial, we explored different ways to delete an empty directory in Python:
- Using
os.rmdir()
: Deletes an empty directory. - Using
pathlib.Path.rmdir()
: Provides an object-oriented approach to deleting an empty directory. - Handling Errors: If the directory is not empty, attempting to delete it using
os.rmdir()
will result in an error.
To delete a non-empty directory, consider using shutil.rmtree()
, but be cautious as it will remove everything inside the directory permanently.