Directory Management
Managing directories is a routine task in Python scripting and automation. Whether you are organizing output files, scanning a project structure, or settin...
Managing Directories in Python: Creation, Listing, and Deletion
Managing directories is a routine task in Python scripting and automation. Whether you are organizing output files, scanning a project structure, or setting up a workspace, Python gives you multiple ways to create, navigate, list, and remove directories.
The two primary tools for directory management are the os module and the pathlib module. Both are part of the standard library, so no installation is needed. pathlib is the more modern and readable choice for new code.
Creating directories is done with os.makedirs() or Path.mkdir(). Using parents=True ensures that all intermediate directories are created, not just the last one. Using exist_ok=True prevents an error if the target already exists:
from pathlib import Path import os
# pathlib approach Path("project/src/utils").mkdir(parents=True, exist_ok=True)
# os approach os.makedirs("project/tests/unit", exist_ok=True)
Listing directory contents is done with os.listdir(), which returns a list of names, or Path.iterdir(), which returns an iterator of Path objects. The Path approach is richer because each result is already a Path object with all its methods available:
from pathlib import Path
for item in Path(".").iterdir(): if item.is_file(): print(f"File: {item.name}") elif item.is_dir(): print(f"Dir: {item.name}")
To search recursively, use Path.rglob("*") or os.walk(). The os.walk() function yields a three-tuple of directory path, list of subdirectory names, and list of file names at each level. It is particularly useful when you need to process every file in an entire tree.
import os for dirpath, dirnames, filenames in os.walk("project"): for filename in filenames: full_path = os.path.join(dirpath, filename) print(full_path)
Removing directories requires the directory to be empty if you use os.rmdir() or Path.rmdir(). For non-empty directories, use shutil.rmtree(), which removes the directory and all its contents recursively. Be careful with this function because it has no undo and permanently deletes everything in the path.
import shutil shutil.rmtree("old_project")
Interview tip: When asked about directory management, mention that shutil.rmtree() is the standard way to delete non-empty directories, but warn that it is irreversible. In production code, it is good practice to log or confirm before calling it. Also mention that you can check if a path is a directory before attempting to delete it to avoid errors.