I quite like using pathlib for path management in python, but the drawback of using this package is that a lot of commands, like shutil.copy
, .move
, the
builtin open
requires a string and not a PosixPath object, giving as error
TypeError: coercing to Unicode: need string or buffer, PosixPath found
The logical solution is of course to use str()
.
My question is how would it be possible (if it would be) to modify pathlib objects such that a call like open(pathlib.PosixPath)
would work without the use of str()
.
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.
The pathlib module of Python makes it very easy and efficient to deal with file paths. The os. path module can also be used to handle path name operations. The difference is that path module creates strings that represent file paths whereas pathlib creates a path object.
PurePath.is_absolute() method –This method is used to check whether the path is absolute or not. This method returns True if the path is absolute otherwise returns False. # Python program to explain PurePath.is_absolute() method. # Import PurePath class from pathlib module. from pathlib import PurePath.
The answer by @Navith is what you should now do in python 3.4. However, PEP-519 is proposed and accepted in python 3.6 to address this valid concern.
This PEP proposes a protocol for classes which represent a file system path to be able to provide a str or bytes representation. Changes to Python's standard library are also proposed to utilize this protocol where appropriate to facilitate the use of path objects where historically only str and/or bytes file system paths are accepted.
So in python 3.6 the standard library methods you refer to now accept Paths, and the answer to your question is use python 3.6.
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