pathlib
The Python pathlib module provides an object-oriented approach to handling file system paths. It offers classes to handle different types of paths, such as POSIX and Windows, making path manipulations more intuitive and less error-prone.
Here’s a quick example:
>>> from pathlib import Path
>>> bin = Path("/usr/bin")
>>> bin.exists()
True
Key Features
- Provides classes for file system path manipulation
- Supports both POSIX and Windows paths
- Offers tools for common path operations like reading, writing, and iterating through files
- Supports high-level file operations like copying and moving with
Path.copy()andPath.move()(Python 3.14+)
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
pathlib.Path |
Class | Represents a file system path |
pathlib.PurePath |
Class | Provides path-handling operations that don’t access the file system |
pathlib.Path.glob() |
Method | Finds all matching pathnames |
pathlib.Path.mkdir() |
Method | Creates a new directory |
Examples
Creating a directory:
>>> dir = Path("new_folder")
>>> dir.mkdir()
>>> dir.exists()
True
Writing and reading a file:
>>> file = Path("example.txt")
>>> file.write_text("Hello, World!")
13
>>> file.read_text()
'Hello, World!'
Iterating over files in a directory:
>>> for file in Path(".").iterdir():
... print(file)
...
Common Use Cases
- Facilitating cross-platform path manipulations
- Navigating and manipulating file system paths
- Reading and writing to files in a path-oriented manner
Real-World Example
Say you want to list all Python files in a directory and its subdirectories:
>>> from pathlib import Path
>>> project_dir = Path("project")
>>> python_files = list(project_dir.rglob("*.py"))
>>> python_files
[PosixPath('project/main.py'), PosixPath('project/utils/helper.py')]
In this example, you use pathlib to recursively find all Python files in a given directory.
Related Resources
Tutorial
Python's pathlib Module: Taming the File System
Handle file and folder paths the modern way with Python pathlib, a built-in module whose semantics work the same on every OS.
For additional information on related topics, take a look at the following resources:
- How to Get a List of All Files in a Directory With Python (Tutorial)
- Using Python's pathlib Module (Course)
- Python Basics: File System Operations (Course)
- Listing All Files in a Directory With Python (Course)
- Working With Files in Python (Tutorial)
- Python's pathlib Module: Taming the File System (Quiz)
- How to Get a List of All Files in a Directory With Python (Quiz)
- Practical Recipes for Working With Files in Python (Course)
- Working With Files in Python (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Oct. 10, 2026