DEV Community

qing
qing

Posted on

2-Minute Python Guide: pathlib (2026)

2-Minute Python Guide: pathlib

Python's pathlib module provides a modern and efficient way to handle file system operations. Here are a few essential path operations you can perform using pathlib:

  • Read and write text files:
from pathlib import Path

file_path = Path("example.txt")
file_path.write_text("Hello, World!")  # write to file
print(file_path.read_text())  # read from file
Enter fullscreen mode Exit fullscreen mode


python

  • Iterate over directory contents:
for item in Path(".").iterdir():
    print(item)
Enter fullscreen mode Exit fullscreen mode
  • Find files using glob patterns:
for file in Path(".").glob("*.txt"):
    print(file)
Enter fullscreen mode Exit fullscreen mode


python

  • Create a new directory:
Path("new_dir").mkdir()
Enter fullscreen mode Exit fullscreen mode

For comparison, here are two examples using os.path:

  • Join paths:
import os
os.path.join("path", "to", "file")  # vs Path("path") / "to" / "file"
Enter fullscreen mode Exit fullscreen mode


python

  • Get file extension:
os.path.splitext("example.txt")  # vs Path("example.txt").suffix
Enter fullscreen mode Exit fullscreen mode

Takeaway: The pathlib module provides a more Pythonic and efficient way to handle file system operations compared to os.path. Its object-oriented approach and methods like read_text, write_text, iterdir, glob, and mkdir make it easier to work with files and directories in Python. Start using pathlib today to simplify your file system operations!


Follow me on Dev.to for daily Python tips and quick guides!

Top comments (0)