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.
# For Python 3.4 and later, pathlib is part of the standard library and does not require installation.Verified import paths — ran on the pinned version, not inferred.
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.
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`.
For Python 2.7, use `pip install pathlib2` and `from pathlib2 import Path`. For Python 3.4+, use the built-in `pathlib` module directly.
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.
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.
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).
For Python 3.4 and newer, ensure you are using a compatible Python version. For Python 3.3 or Python 2.x, install the backport using `pip install pathlib`. If on Python 2.7, `pathlib2` is a more maintained alternative: `pip install pathlib2`.
Rename your custom Python file to something other than `pathlib.py` to avoid shadowing the standard library module.
Verify that you have correctly imported `from pathlib import Path`. If you have other path-related libraries installed, ensure there are no naming conflicts or shadowing, and fully qualify the import if necessary (e.g., `import pathlib; p = pathlib.Path('foo') / 'bar'`).No dependency data recorded yet.