Last modified: Mar 19, 2025 By Alexander Williams

Python Pathlib rmdir() Explained

Python's pathlib module simplifies file and directory operations. One of its useful methods is rmdir(). This method removes empty directories. Let's explore how it works.

What is Pathlib rmdir()?

The rmdir() method is part of the pathlib.Path class. It deletes an empty directory. If the directory is not empty, it raises an error. This ensures you don't accidentally delete important files.

Syntax of rmdir()

The syntax is straightforward. You call rmdir() on a Path object. Here's the basic structure:


from pathlib import Path

# Create a Path object
directory = Path("example_dir")

# Remove the directory
directory.rmdir()
    

Example: Removing an Empty Directory

Let's see rmdir() in action. First, create an empty directory using mkdir(). Then, remove it with rmdir().


from pathlib import Path

# Create a directory
directory = Path("empty_dir")
directory.mkdir()

# Check if the directory exists
if directory.exists():
    print("Directory exists. Removing it now.")
    directory.rmdir()
    print("Directory removed.")
    

Directory exists. Removing it now.
Directory removed.
    

Handling Errors with rmdir()

If the directory is not empty, rmdir() raises an OSError. Always check if the directory is empty before calling rmdir(). Use is_dir() to confirm it's a directory.


from pathlib import Path

# Create a directory with a file
directory = Path("non_empty_dir")
directory.mkdir()
file_path = directory / "example.txt"
file_path.touch()

# Attempt to remove the directory
try:
    directory.rmdir()
except OSError as e:
    print(f"Error: {e}")
    

Error: [Errno 39] Directory not empty: 'non_empty_dir'
    

Best Practices for Using rmdir()

Always ensure the directory is empty before using rmdir(). You can list the directory contents using iterdir(). Also, use exists() to verify the directory exists before deletion.

Conclusion

The rmdir() method is a powerful tool for managing directories in Python. It ensures safe deletion of empty directories. Always handle errors and verify directory status to avoid issues. For more advanced path operations, explore joinpath() and resolve().