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
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
pathlib.Path |
Class | Represents a file system path |
pathlib.PurePath |
Class | Provides an abstract class for system-agnostic paths |
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!")
>>> 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
[Path('project/main.py'), Path('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
Python's pathlib module enables you to handle file and folder paths in a modern way. This built-in module provides intuitive semantics that work the same way on different operating systems. In this tutorial, you'll get to know pathlib and explore common tasks when interacting with paths.
For additional information on related topics, take a look at the following resources:
- Working With Files in Python (Tutorial)
- How to Get a List of All Files in a Directory With Python (Tutorial)
- Using Python's pathlib Module (Course)
- Practical Recipes for Working With Files in Python (Course)
- Listing All Files in a Directory With Python (Course)
By Leodanis Pozo Ramos • Updated July 16, 2025