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
python
- Iterate over directory contents:
for item in Path(".").iterdir():
print(item)
- Find files using glob patterns:
for file in Path(".").glob("*.txt"):
print(file)
python
- Create a new directory:
Path("new_dir").mkdir()
For comparison, here are two examples using os.path:
- Join paths:
import os
os.path.join("path", "to", "file") # vs Path("path") / "to" / "file"
python
- Get file extension:
os.path.splitext("example.txt") # vs Path("example.txt").suffix
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)