What it is
Pathlib is a Python standard library module that provides an object-oriented interface for working with filesystem paths. It simplifies file and directory manipulations across different operating systems.
Pathlib allows you to create, manipulate, and query file paths using Path objects. It supports operations like checking existence, reading/writing files, creating directories, iterating over directories, and handling path joins in a platform-independent way.
Installation
Included in Python standard library (Python 3.4+)Getting started
The smallest useful thing you can do with it, and what each part means.
from pathlib import Path
path = Path('/home/user/docs')
print(path.exists())from pathlib import Path
path = Path('/home/user') / 'docs' / 'file.txt'
print(path)from pathlib import Path
path = Path('/home/user/docs')
for file in path.iterdir():
print(file.name)Advanced usage
Where the library earns its place over a simpler alternative.
from pathlib import Path
path = Path('example.txt')
path.write_text('Hello, Pathlib!')
content = path.read_text()
print(content)from pathlib import Path
path = Path('new_folder')
path.mkdir(exist_ok=True)from pathlib import Path
path = Path('example.txt')
print(path.is_file())
print(path.is_dir())
print(path.suffix)from pathlib import Path
path = Path('/home/user/docs')
for txt_file in path.glob('*.txt'):
print(txt_file)from pathlib import Path
path = Path('/home/user/docs')
for py_file in path.rglob('*.py'):
print(py_file)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- FileNotFoundError
- Ensure the file or directory exists before attempting to read or modify it.
- PermissionError
- Check that the program has the necessary permissions to read/write the file or directory.
- IsADirectoryError / NotADirectoryError
- Verify whether the path is a file or a directory before performing file-specific or directory-specific operations.
Best practices
- Prefer Path objects over string paths for cleaner and safer code.
- Use `/` operator to join paths instead of `os.path.join()` for readability.
- Leverage `exists()`, `is_file()`, and `is_dir()` to validate paths before operations.
- Use `mkdir(exist_ok=True, parents=True)` for creating nested directories safely.
- Combine Pathlib with `shutil` for advanced file operations like copy and move.
Background
Why it exists, and what it was reacting to.
Pathlib was introduced in Python 3.4 to offer a more intuitive, object-oriented approach to handling filesystem paths compared to the traditional `os.path` module. It unifies the handling of files and directories, making code cleaner, more readable, and portable.
