Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to simplify use of pathlib objects to work with functions looking for strings

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().

like image 324
Pierpaolo Avatar asked Jun 06 '15 02:06

Pierpaolo


People also ask

How does Pathlib path work?

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.

What is the use of Pathlib module in Python?

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.

What is PurePath in Python?

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.


1 Answers

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.

like image 79
Mr_and_Mrs_D Avatar answered Sep 21 '22 20:09

Mr_and_Mrs_D