Python Forum

Full Version: Is pathlib a viable replacement for os.path?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So far I have used only os.path, and as I have stumbled over that topic in a guide I am reading, it got me wondering...
Can pathlib replace os.path completely, even doing a better job at it maybe?
Reading about os.path reminded me of much praise for pathlib expressed on the forums, with examples shown as well.
A long time ago (2004 may be) there was a path module written by Jason Orendorff (older version) that many people included in their projects. Various alternative implementations existed such as this one. For personal projects, I had my own version of this module, obtained by adding more and more methods to the Path class.

The main benefit of these classes is the programmer's comfort. It is satisfying to build paths by using the division operator instead of joining strings, it is comfortable to have features available by calling an object's method.

If you look at python's pathlib, you'll notice that the devs have been very careful about which methods to include and which methods not to include in the classes. It makes the Path class less attractive that it could be, at the same time, this care is understandable. The Path class will probably slowly add important features.

I try to use pathlib as often as I can because of this past experience with other Path classes which saved me a lot of pain in my programs. I think yes, pathlib can completely replace os.path, and using os.path has a taste of backward compatibility!
Path (of pathlib) instantiates a concrete path for the platform the code is running on.
This means both purepaths (purely computational operations) and Concrete ( which inherit from pure paths but also provide I/O operations)

I have been using pathlib almost exclusively for about two months now, and really like how clean it is.

Since it is 100% object oriented, you can do things like:
from pathlib import Path
home = Path('.')
datapath = home / 'data'
jsonpath = datapath / 'json'
>>> imagepath = home / '..' / 'images'
>>> image_list = [x for x in imagepath.iterdir()]
>>> for image in image_list:
...     print(image)
...
..\images\advancedsplash.png
..\images\AG00028_.gif
..\images\AG00039_.gif
..\images\AG00178_.gif
..\images\AG00183_.gif
..\images\AG00185_.gif
..\images\aquabutton.png
..\images\aquachecked.ico
..\images\aquaflagged.ico
..\images\aquanotchecked.ico
>>>>>> imagepath.resolve()
WindowsPath('Z:/python/q-t/r/RfcViewerJupyterVenv/RfcViewerJupyter/images')
>>>
Thank you both for answers! I can confidently walk around os.path in favour of pathlib from now :)
I only want to add that there is an issue (or bug) with pathlib: if you try to subclass directly pathlib.Path in order to add your own custom methods, it FAILS!

A simple solution seems to subclass the concrete class type(pathlib.Path()) instead.