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

  1. Import Path: from pathlib import Path
  2. Create a path object: p = Path("/home/user/documents")
  3. Join paths: file = p / "report.txt"
  4. Read content: content = file.read_text()
  5. 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