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:
Python
>>> 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:
Python
>>> dir = Path("new_folder")
>>> dir.mkdir()
>>> dir.exists()
True
Writing and reading a file:
Python
>>> file = Path("example.txt")
>>> file.write_text("Hello, World!")
>>> file.read_text()
'Hello, World!'
Iterating over files in a directory:
Python
>>> 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:
Python
>>> 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.