{
    "slug": "py_pathlib",
    "term": "pathlib & Modern File Handling",
    "category": "python",
    "difficulty": "beginner",
    "short": "pathlib.Path provides an object-oriented API for filesystem operations — replacing os.path string manipulation with readable, chainable, and cross-platform path handling.",
    "long": "pathlib (Python 3.4+) represents paths as Path objects with methods: / operator joins paths, .read_text() / .write_text() / .read_bytes(), .exists() / .is_file() / .is_dir(), .glob() / .rglob() for pattern matching, .stem / .suffix / .parent / .name attributes, .mkdir(parents=True, exist_ok=True). Avoids the fragile string concatenation of os.path.join(). Works correctly on Windows (backslash) and Unix (forward slash). Use Path objects from the start — do not mix Path and string manipulation.",
    "aliases": [
        "pathlib",
        "Path",
        "os.path replacement",
        "filesystem Python"
    ],
    "tags": [
        "python",
        "filesystem",
        "stdlib"
    ],
    "misconception": "os.path is equivalent to pathlib — os.path uses string manipulation and requires knowing the right function for each operation; pathlib provides an intuitive object model that reads like natural language.",
    "why_it_matters": "os.path.join(base, 'sub', 'file.txt') is verbose and error-prone — Path(base) / 'sub' / 'file.txt' is readable, cross-platform, and provides richer functionality.",
    "common_mistakes": [
        "Mixing string concatenation with Path objects — always use / operator or Path() constructor.",
        "Not using exist_ok=True in mkdir — raises if directory exists.",
        "glob() not being recursive — use rglob('**/*.py') or rglob with a pattern for recursive matching.",
        "Converting Path to string with str() when passing to legacy APIs — unnecessary in modern Python."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "py_context_managers",
        "bash_scripting",
        "linux_file_system"
    ],
    "prerequisites": [
        "py_error_handling",
        "linux_file_system",
        "bash_scripting"
    ],
    "refs": [
        "https://docs.python.org/3/library/pathlib.html"
    ],
    "bad_code": "import os\n\n# String-based path manipulation — fragile:\nbase = '/var/www/app'\nconfig_path = base + '/config' + '/settings.json'  # Wrong on Windows\nif os.path.exists(config_path):\n    with open(config_path) as f:\n        data = f.read()\nos.makedirs(os.path.join(base, 'logs'), exist_ok=True)",
    "good_code": "from pathlib import Path\n\nbase = Path('/var/www/app')\nconfig_path = base / 'config' / 'settings.json'  # / operator, cross-platform\n\nif config_path.exists():\n    data = config_path.read_text(encoding='utf-8')  # No with-open needed\n\n(base / 'logs').mkdir(parents=True, exist_ok=True)\n\n# Find all Python files recursively:\nfor py_file in base.rglob('*.py'):\n    print(py_file.stem, py_file.suffix)",
    "quick_fix": "Use pathlib.Path instead of os.path for all file operations — Path('/etc') / 'hosts' is cleaner than os.path.join('/etc', 'hosts'), and Path methods are object-oriented and expressive",
    "severity": "low",
    "effort": "low",
    "created": "2026-03-16",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/py_pathlib",
        "html_url": "https://codeclaritylab.com/glossary/py_pathlib",
        "json_url": "https://codeclaritylab.com/glossary/py_pathlib.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[pathlib & Modern File Handling](https://codeclaritylab.com/glossary/py_pathlib) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/py_pathlib"
            }
        }
    }
}