is the proper way to get the plain string path of a pathlib.PurePath object or pathlib.Path object to pass it to str() and use what that returns? that is all i can find. the documentation (i have the 3.5.2 PDF) only describes the .name attribute for part of the path. i suppose i could join the .parts value in some way.
import pathlib
...
fp = pathlib.Path('foo/bar')
...
fn = str(fp)
this is only the 2nd time using this module and the 1st time didn't need this.
In [1]: import pathlib
In [2]: path = pathlib.Path('.')
In [3]: full_path = path.absolute()
In [4]: my_path = full_path.as_posix()
In [5]: print(my_path)
/home/victor
In [6]: type(my_path)
Out[6]: str
(Mar-20-2018, 11:08 AM)Larz60+ Wrote: [ -> ]or use path.resolve()
that appears to return a Path object instead of a string, although it might be good to apply this first.
edit:
maybe ... if the object does not exist, .resolve() raises a fit.
just to be sure it's understood, the code has a pathlib.Path() or pathlib.PurePath() object and needs a string to work with and .name is not the full path.
Since pathlib returns an object, you can also do things like:
homepage = Path('.')
doc = homepage / '..' / 'doc'
# Create the directory if it doesn't already exist
doc.mkdir(exist_ok=True)
datapath = homepage / 'data'
datapath.mkdir(exist_ok=True)
input_file = datapath / 'MyFile.txt'
with input_file.open() as f:
for line in f:
print(line)
Hah, didn't know that it has open() method!
What I don't like is the method
relative_to
.
This method works only, if the given argument is a subpath:
pathlib.Path.home().relative_to('/dev')
Error:
ValueError: '/home/andre' does not start with '/dev'
Doing the same with the os.path
home = os.path.expanduser('~')
print(os.path.relpath(home, '/dev'))
Output:
../home/andre
but i needed a real string and the only thing i could find was attribute method .__str__() which is what str() uses.
str(your_path.resolve())
The method resolve
returns a new Path object.
Path objects have a magic method for str and bytes (__str__, __bytes__).
str(pathobject) -> returns a str of the path