DEV Community

qing
qing

Posted on • Edited on

TIL: Python's `pathlib` is way better than `os.path` for file operations

TIL: Python's pathlib is way better than os.path for file operations

Hey fellow devs, if you're still using os.path for file operations in Python, it's time to upgrade to pathlib. I recently made the switch and I'm loving the simplicity and readability it brings to my code.

Let's compare some examples. With os.path, joining paths can be a bit clunky:

import os
path = os.path.join('dir', 'subdir', 'file.txt')
Enter fullscreen mode Exit fullscreen mode

Meanwhile, pathlib makes it a breeze:

import pathlib
path = pathlib.Path('dir') / 'subdir' / 'file.txt'
Enter fullscreen mode Exit fullscreen mode

Need to check if a file


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


喜欢这篇文章?关注获取更多Python自动化内容!

Top comments (0)