{"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":"python","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,"search_vec":"'/2.7':60 '1.0.1':48 '2.6':59 '3.3':54 '3.4':42 'backport':51 'code':20 'compar':25 'concis':24 'earlier':56 'evolv':65 'featur':64 'file':75 'filesystem':13,70 'handl':12 'interfac':10 'io':72 'librari':39,74 'like':29 'make':19 'manag':76 'manipul':17 'modul':4,28,62 'object':8 'object-ori':7 'orient':9 'os.path':30 'packag':45 'part':34 'path':14,16,71 'pathlib':1,3,46 'provid':5 'pypi':44 'python':36,41,53,58,68 'readabl':22 'simplifi':15 'sinc':40 'standard':38,73 'tradit':27 'version':47,69","created_at":"2026-04-09T03:55:49.104556+00:00","updated_at":"2026-04-16T17:54:52.181429+00:00","problems":[{"fix":"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`.","cause":"`pathlib` became a standard library module in Python 3.4. This error typically occurs when running code with Python 2.x or an older Python 3.x version (before 3.4) without installing the backport, or when the `pathlib` backport package is not installed in the active environment.","error":"ImportError: No module named pathlib"},{"fix":"Rename your custom Python file to something other than `pathlib.py` to avoid shadowing the standard library module.","cause":"This error commonly arises when a user-created Python file is named `pathlib.py` in the same directory as the script being run, or within Python's import path. This causes the interpreter to import the local, empty `pathlib.py` instead of the standard library `pathlib` module, leading to the `Path` class not being found.","error":"AttributeError: module 'pathlib' has no attribute 'Path'"},{"fix":"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'`).","cause":"This error occurs when the `Path` object being used is not the `pathlib.Path` class from the standard library, often due to shadowing by a custom or another library's `Path` class. The standard `pathlib.Path` class *does* support the `/` operator with strings.","error":"TypeError: unsupported operand type(s) for /: 'Path' and 'str'"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"1.0.1","cli_name":"","cli_version":null,"type":"library","homepage":"https://pathlib.readthedocs.org/","github":null,"docs":null,"changelog":null,"pypi":"https://pypi.org/project/pathlib/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["serialization","data"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-27","next_check":"2026-07-28","install_tag":null}}