Sub topic 3
Creating and Listing Directories
Assume basic Python functions, loops, and file-system concepts. This chapter uses Path objects and changes a temporary directory so the examples are safe to run.
Creating directories and finding files
mkdir() creates a directory. Use parents=True to create missing parent directories and exist_ok=True when an existing directory is acceptable. iterdir() lists immediate children. glob() searches one directory level, while rglob() searches recursively.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as name:
root = Path(name)
reports = root / "data" / "reports"
reports.mkdir(parents=True, exist_ok=True)
(reports / "daily.txt").write_text("today\n", encoding="utf-8")
(reports / "monthly.csv").write_text("total\n", encoding="utf-8")
(reports / "old").mkdir()
print(sorted(path.name for path in root.iterdir()))
print(sorted(path.name for path in root.glob("data/reports/*.txt")))
print(sorted(path.name for path in root.rglob("*.txt")))File operations and metadata
rename() moves a path and can rename it. replace() also renames it but replaces an existing destination. unlink() deletes a file, and rmdir() removes an empty directory. stat() returns metadata such as size and modification time.
entry = reports / "daily.txt"
archived = reports / "archived.txt"
entry.rename(archived)
print(archived.stat().st_size)
archived.unlink()
(reports / "old").rmdir()Interoperability and platform differences
Many older APIs accept strings, but Path implements the path-like protocol. Pass str(path) or os.fspath(path) when an API specifically requires a string.
PurePosixPath and PureWindowsPath manipulate paths without accessing the file system. They are useful for parsing paths from another operating system.
import os
from pathlib import PureWindowsPath
path = Path("logs") / "app.log"
print(os.fspath(path))
print(PureWindowsPath("C:/Users/Ana/app.log").drive)Common pitfalls
- An absolute segment discards earlier segments:
Path("safe") / "/etc"becomes/etc. rglob()can traverse more data than expected. Restrict its starting directory.with TemporaryDirectory()deletes its contents when the block ends.rmdir()fails on non-empty directories; delete their files first.
Exercise
Which method searches a directory tree recursively for matching names?
Show answer
rglob(). Use glob() when the search should remain at the selected directory level.