{"id":1617,"library":"pathlib","title":"pathlib","description":"The `pathlib` module provides an object-oriented interface for handling filesystem paths, simplifying path manipulations and making code more readable and concise compared to traditional modules like `os.path`. It has been part of Python's standard library since Python 3.4. The PyPI package 'pathlib' (version 1.0.1) is a backport for Python 3.3 and earlier, and Python 2.6/2.7. The module's features evolve with each Python version.","status":"active","version":"1.0.1","language":"en","source_language":"en","source_url":"https://docs.python.org/3/library/pathlib.html","tags":["filesystem","paths","io","standard library","file management"],"install":[{"cmd":"# For Python 3.4 and later, pathlib is part of the standard library and does not require installation.","lang":"bash","label":"Python 3.4+"},{"cmd":"pip install pathlib","lang":"bash","label":"Python < 3.4 (backport)"},{"cmd":"pip install pathlib2","lang":"bash","label":"Python 2.7 (recommended backport)"}],"dependencies":[],"imports":[{"note":"Importing Path directly is generally preferred for brevity and clarity.","wrong":"import pathlib; pathlib.Path('file.txt')","symbol":"Path","correct":"from pathlib import Path"}],"quickstart":{"code":"import os\nfrom pathlib import Path\n\n# Create a path object\ncurrent_dir = Path.cwd()\nexample_dir = current_dir / \"my_data\"\nexample_file = example_dir / \"report.txt\"\n\n# Ensure the directory exists\nexample_dir.mkdir(exist_ok=True)\n\n# Write to a file\nexample_file.write_text(\"This is a test report.\\n\")\nprint(f\"Created file: {example_file.resolve()}\")\n\n# Read from a file\ncontent = example_file.read_text()\nprint(f\"File content: {content.strip()}\")\n\n# Check properties\nprint(f\"Is it a file? {example_file.is_file()}\")\nprint(f\"File name: {example_file.name}\")\nprint(f\"File suffix: {example_file.suffix}\")\nprint(f\"Parent directory: {example_file.parent.name}\")\n\n# Clean up (optional)\nexample_file.unlink()\nexample_dir.rmdir()\nprint(\"Cleaned up example directory and file.\")","lang":"python","description":"This quickstart demonstrates creating a `Path` object, ensuring a directory exists, writing and reading text to/from a file, and accessing common path properties. It concludes with a cleanup of the created directory and file."},"warnings":[{"fix":"Pass `Path` objects directly to functions that support `os.PathLike` (which `Path` implements). Convert to string only when absolutely necessary for older APIs that strictly require `str`.","message":"Avoid converting `Path` objects to strings (`str(path_obj)`) too early, as this loses all the benefits of the `Path` object's methods and object-oriented features. Most modern Python functions and libraries (since Python 3.6, including `open()`, `shutil.copy()`, `json.load`/`json.dump`, `subprocess.run`) natively accept `Path` objects.","severity":"gotcha","affected_versions":"Python 3.6+"},{"fix":"For Python 2.7, use `pip install pathlib2` and `from pathlib2 import Path`. For Python 3.4+, use the built-in `pathlib` module directly.","message":"The `pathlib` PyPI backport (version 1.0.1) is no longer maintained. For Python 2.7, `pathlib2` is the recommended and more actively maintained backport to provide similar functionality to the standard library `pathlib`.","severity":"deprecated","affected_versions":"Python 2.6, 2.7, 3.2, 3.3"},{"fix":"Always ensure the directory exists before calling `iterdir()` if the path might not exist. Be aware of potential subtle behavioral changes across Python versions when relying on specific iterator or generator evaluation timings.","message":"The semantics of certain methods, like `Path.iterdir()`, can change between major Python versions. For instance, in Python 3.13, `Path.iterdir()` started evaluating a portion of the generator eagerly, potentially raising `FileNotFoundError` earlier if the directory doesn't exist, which was not the case in 3.12 (lazy evaluation).","severity":"breaking","affected_versions":"Python 3.13+"},{"fix":"For general file system operations on the current system, always use `pathlib.Path` which instantiates the correct concrete path for the platform. Only use `PurePath`, `PurePosixPath`, or `PureWindowsPath` when you explicitly intend to manipulate paths purely computationally without touching the filesystem, or to represent paths for a different OS.","message":"While `pathlib` provides `PurePosixPath` and `PureWindowsPath` for platform-agnostic path manipulation, using them explicitly can lead to `NotImplementedError` if you try to instantiate a platform-specific concrete path (e.g., `WindowsPath` on Unix) directly or if I/O operations are attempted with a `PurePath` object. Use `Path` for platform-appropriate concrete paths unless you specifically need pure path operations without I/O or cross-platform path *representation*.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Prioritize `pathlib` methods (e.g., `/` operator for joining, `.exists()`, `.is_file()`, `.glob()`, `.rglob()`, `.mkdir()`, `.unlink()`) over `os.path` functions. Only fall back to `os` or `shutil` when `pathlib` does not offer equivalent functionality (e.g., `shutil.copy` for copying files efficiently).","message":"Mixing `pathlib` objects with functions from the `os` or `os.path` modules can negate `pathlib`'s benefits, often requiring unnecessary `str()` conversions. `pathlib` aims to consolidate and replace most `os.path` functionality.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}