More than an answer to the question, I am trying to learn how to make sense of the Official Python Documentation.
I understand that Path
inherits from PurePath
, but I am unable to understand when to use which and why there is PurePath
& Path
instead of one.
In the list of alternatives, most are suggesting Path
while some are suggesting Pathlib
.
I am looking at os.path.dirname()
where they are suggesting PurePath.parent
. But I am getting the same result when I run pathlib.PurePath(file).parent.name
& pathlib.Path(file).parent.name
.
So, why did they use PurePath
for some & Path
for most. Why did they not suggest Path.parent
instead of PurePath.parent
?
The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.
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. More powerful, with most necessary methods and properties available directly on the object.
Pure paths. Pure path objects provide path-handling operations which don't actually access a filesystem. There are three ways to access these classes, which we also call flavours: class pathlib. PurePath (*pathsegments)
The OS library will return a string, whereas the Pathlib will return an object of PosixPath. The benefit of having PosixPath returned is that we can directly use the returned object to do a lot more further operations.
First paragraph in pathlib documentation states:
Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.
Pure path objects provide path-handling operations which don’t actually access a filesystem.
Concrete paths are subclasses of the pure path classes. In addition to operations provided by the former(pure path), they also provide methods to do system calls on path objects.
In conclusion, PurePath
acts like string (remove parts of path, join with another path, get parents etc). To remove directory, search directory, create a file or write to file, you must use Path
object.
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