--- Files And Paths With `pathlib` • Python Cabinet

Files And Paths With pathlib

  • pathlib.Path treats file paths as objects instead of fragile strings—use / to join paths, .glob() to find files, and .read_text() / .write_text() for quick I/O.

How it works

Old Python code joins folder strings with os.path.join() and walks trees with os.walk(). Modern Python uses pathlib.Path, which handles / cleanly on macOS, Linux, and Windows:

from pathlib import Path

policies_dir = Path("data/policies")
for file_path in policies_dir.glob("*.md"):
    text = file_path.read_text(encoding="utf-8")
    sections = text.split("\n## ")

Use .rglob("*.md") instead of .glob("*.md") when you also want to search subdirectories recursively.

What can go wrong

  • Relative paths depend on cwd: Path("data/policies") breaks if you launch the script from outside the project root. Anchor paths with Path(__file__).resolve().parent when scripts might be called from anywhere.
  • Silent decode errors: Passing errors="ignore" (as in retrieval.py) hides corrupted bytes; let UTF-8 decoding fail loudly unless you expect messy input.

Referenced code

From app/semantic_retrieval.py in ai-security-lab:

policies_dir = Path("data/policies")

for file_path in policies_dir.glob("*.md"):
    if file_path.exists():
        content = file_path.read_text()
        sections = content.split("\n## ")

Evidence: app/semantic_retrieval.py and app/retrieval.py in ai-security-lab. Related: Semantic document retrieval and Keyword document retrieval.