A comprehensive, production-grade Python reference suite demonstrating directory creation, inspection/scanning, metadata management, deletion, and temporary folder lifecycle using the Python Standard Library (os, shutil, tempfile, and pathlib.Path).
This directory has been completely refactored and expanded from 2 simple scripts (create_folder.py, create_new_folder.py) into a structured, PEP 8-compliant 5-tier architecture:
create_directory_ops.py: Safe single and multi-level directory creation (os.mkdir,os.makedirs,Path.mkdir).scan_directory_ops.py: Efficient directory listings, file metadata retrieval, recursive tree walking, and globbing (os.listdir,os.scandir,os.walk,Path.glob).manage_directory_ops.py: Directory renaming (Path.rename), moving (shutil.move), and cumulative folder size calculation.remove_directory_ops.py: Safe empty folder deletion (Path.rmdir) and recursive directory tree removal (shutil.rmtree).temp_directory_ops.py: Auto-cleaning temporary directories (tempfile.TemporaryDirectory) and explicit temp directory creation (tempfile.mkdtemp).test_folders.py: Automated unittest test suite validating all 5 directory operation modules.
os: Standard operating system interface for POSIX and Windows directory manipulations (mkdir,makedirs,listdir,scandir,walk,rmdir).pathlib.Path: Object-oriented filesystem path abstraction providing clean syntax for directory operations (mkdir,rename,rmdir,glob,rglob).shutil: High-level file and directory operations for moving (move) and recursive deletion (rmtree).tempfile: Secure temporary directory generation (TemporaryDirectory,mkdtemp).
Creates a single directory at the specified path. Raises FileExistsError if the directory already exists.
import os
os.mkdir("new_folder")Recursively creates nested directory trees. When exist_ok=True, suppresses FileExistsError if the target directory exists.
import os
os.makedirs("parent/child/grandchild", exist_ok=True)Object-oriented method to create directories. Set parents=True for nested directory trees and exist_ok=True for safe re-runs.
from pathlib import Path
Path("parent/child").mkdir(parents=True, exist_ok=True)Returns a list of entry names (files and directories) contained in the specified directory.
import os
entries = os.listdir(".")
print(entries)Yields DirEntry objects providing file attributes without requiring extra system calls. Efficient for large directory structures.
Attributes & Methods on DirEntry:
.name: Base entry name..path: Full entry path string..is_dir(): ReturnsTrueif entry is a directory..is_file(): ReturnsTrueif entry is a file..stat(): Returnsos.stat_result(contains.st_size,.st_mtime).
import os
with os.scandir(".") as entries:
for entry in entries:
print(f"Name: {entry.name}, Is Dir: {entry.is_dir()}")Generates file names in a directory tree by walking either top-down or bottom-up. Yields 3-tuples: (dirpath, dirnames, filenames).
import os
for root, dirs, files in os.walk("."):
print(f"Directory: {root} | Subfolders: {len(dirs)} | Files: {len(files)}")Iterates over directory entries matching pattern. rglob(pattern) is equivalent to glob("**/" + pattern).
from pathlib import Path
# Non-recursive match
py_files = list(Path(".").glob("*.py"))
# Recursive match
all_py_files = list(Path(".").rglob("*.py"))Renames a directory to target. Raises FileNotFoundError if source does not exist.
from pathlib import Path
src = Path("old_name")
dest = Path("new_name")
src.rename(dest)Recursively moves a directory or file to another destination, cross-filesystem compatible.
import shutil
shutil.move("folder_a", "destination_folder/folder_a")Computes cumulative size of all contained files in a directory tree.
import os
from pathlib import Path
def get_directory_size(path: Path) -> int:
total = 0
for root, _, files in os.walk(path):
for f in files:
total += (Path(root) / f).stat().st_size
return totalRemoves an empty directory. Raises OSError (Directory not empty) if files or subdirectories remain inside.
from pathlib import Path
Path("empty_folder").rmdir()Deletes an entire directory tree recursively, removing all contained files and subdirectories.
import shutil
shutil.rmtree("non_empty_folder")Context manager creating a temporary directory. Automatically cleans up directory and contents upon exiting the with block.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory(prefix="app_") as temp_dir:
temp_path = Path(temp_dir)
(temp_path / "temp.txt").write_text("Data")
# Auto-deleted hereCreates a temporary directory requiring explicit deletion via shutil.rmtree.
import shutil
import tempfile
temp_path = tempfile.mkdtemp(prefix="manual_")
# ... use directory ...
shutil.rmtree(temp_path)| Module | Primary Standard Functions | Description |
|---|---|---|
create_directory_ops.py |
os.mkdir, os.makedirs, Path.mkdir |
Demonstrates safe single & multi-level directory creation. |
scan_directory_ops.py |
os.listdir, os.scandir, os.walk, Path.glob |
Scans directory contents, inspects metadata, and walks trees. |
manage_directory_ops.py |
Path.rename, shutil.move, Path.stat |
Handles directory renaming, moving, and folder size calculations. |
remove_directory_ops.py |
Path.rmdir, shutil.rmtree |
Demonstrates safe empty removal and recursive tree deletion. |
temp_directory_ops.py |
tempfile.TemporaryDirectory, tempfile.mkdtemp |
Demonstrates managed and manual temporary directory handling. |
test_folders.py |
unittest.TestCase |
Unit tests for all directory management functionality. |
python3 create_directory_ops.py
python3 scan_directory_ops.py
python3 manage_directory_ops.py
python3 remove_directory_ops.py
python3 temp_directory_ops.pypython3 -m unittest test_folders.pypython3 -m py_compile *.py