How to use Python pathlib module for file operations
· Category: Python Programming
Short answer
Use pathlib.Path to represent filesystem paths as objects. It supports chaining methods like read_text(), write_text(), and mkdir(). For reading and writing files in general, see python read write files. For error handling, see python error handling try except.
Steps
- Import Path:
from pathlib import Path - Create a path object:
p = Path("/home/user/documents") - Join paths:
file = p / "report.txt" - Read content:
content = file.read_text() - Create a directory:
p.mkdir(parents=True, exist_ok=True)
Tips
- pathlib is available in Python 3.4+ and recommended over os.path
- Use
Path.glob()for pattern matching - For asynchronous file operations, see python asyncio