DEV Community

Cover image for Stop Using `os.path` in Python (Use pathlib Instead)
Sameer Qaiser
Sameer Qaiser

Posted on

Stop Using `os.path` in Python (Use pathlib Instead)

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)
Enter fullscreen mode Exit fullscreen mode

The New Way (pathlib):

from pathlib import Path
path = Path("folder") / "subfolder" / "file.txt"
exists = path.exists()
name = path.name
Enter fullscreen mode Exit fullscreen mode

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)