If you are still using os.path to navigate directories in Python, you are doing things the hard way.
Enter pathlib. It's built into Python and makes working with file paths so much cleaner. Here's a quick comparison:
The Old Way (os.path):
import os
path = os.path.join("folder", "subfolder", "file.txt")
exists = os.path.exists(path)
name = os.path.basename(path)
The New Way (pathlib):
from pathlib import Path
path = Path("folder") / "subfolder" / "file.txt"
exists = path.exists()
name = path.name
It uses the / operator to join paths (works on Windows and Mac automatically), and it treats paths as objects, not just strings.
Are you team os.path or team pathlib? Let me know below!
Top comments (0)