pathlib.Path & TraversalModern Python uses the object-oriented pathlib module for file system path operations, replacing legacy os.path string manipulations.
pathlib.Path Operationsflowchart TD
A["Path('src/module/app.py')"] --> B[".name -> 'app.py'"]
A --> C[".stem -> 'app'"]
A --> D[".suffix -> '.py'"]
A --> E[".parent -> Path('src/module')"]
pathlib MethodsPath.mkdir(parents=True, exist_ok=True): Create directory hierarchy.Path.glob(pattern): Match files matching glob pattern in directory.Path.rglob(pattern): Recursively match files in directory tree.Path.is_file() / Path.is_dir() / Path.exists(): Inspection checks.from pathlib import Path
from typing import List
def inspect_directory_structure(base_dir: Path) -> List[Path]:
"""Recursively scan directory for Python files using rglob."""
python_files = list(base_dir.rglob("*.py"))
return python_files
if __name__ == "__main__":
current_dir = Path.cwd()
print(f"Current Working Directory: {current_dir}")
print(f"Directory Name: {current_dir.name}")
print(f"Parent Directory: {current_dir.parent}")
# Create temporary subdirectories
sub_dir = current_dir / "scratch_test_dir" / "nested"
sub_dir.mkdir(parents=True, exist_ok=True)
print(f"Created Nested Directory: {sub_dir.exists()}")
# Cleanup
if (current_dir / "scratch_test_dir").exists():
import shutil
shutil.rmtree(current_dir / "scratch_test_dir")
/ Operator for Path Joining: Use Path("dir") / "subdir" / "file.txt" instead of os.path.join().parents=True and exist_ok=True: path.mkdir(parents=True, exist_ok=True) prevents FileExistsError and creates missing parent folders.rglob() for Recursive Searches: Path.rglob("*.txt") is clean and fast for searching nested folders.Write a function that iterates over all files in the current working directory using Path.cwd().iterdir() and prints file names and sizes in bytes.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With