I found the pathlib syntax - or is it the python syntax - surprising. I'd like to know how this makes the forward slash '/' act as a joiner of windowspaths etc. Does it override/overload '/' ? It seems to be in a magical context, the slash is between a WindowsPath type object and a string. If I try between 2 strings it fails to join the 2 strings (i.e. "123" / "123" -> fails)
p=pathlib.Path(".") p Out[66]: WindowsPath('.') p.cwd() Out[67]: WindowsPath('C:/Users/user1') p.cwd() / "mydir" Out[68]: WindowsPath('C:/Users/user1/mydir')
Since Python 3.4, pathlib has been available in the standard library. With pathlib , file paths can be represented by proper Path objects instead of plain strings as before. These objects make code dealing with file paths: Easier to read, especially because / is used to join paths together.
Pathlib module in Python provides various classes representing file system paths with semantics appropriate for different operating systems. This module comes under Python's standard utility modules. Path classes in Pathlib module are divided into pure paths and concrete paths.
The pathlib library is included in all versions of python >= 3.4.
The Path class has a __truediv__
method that returns another Path. You can do the same with your own classes:
>>> class WeirdThing(object): def __truediv__(self, other): return 'Division!' >>> WeirdThing() / WeirdThing() 'Division!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With