Asked By – trainset
Is there something similar to
os.path.dirname(path), but in pathlib?
Now we will see solution for issue: How to get folder name, in which given file resides, from pathlib.path?
It looks like there is a
parents element that contains all the parent directories of a given path. E.g., if you start with:
>>> import pathlib >>> p = pathlib.Path('/path/to/my/file')
p.parents is the directory containing
>>> p.parents PosixPath('/path/to/my')
p.parents will be the next directory up:
>>> p.parents PosixPath('/path/to')
p.parent is another way to ask for
p.parents. You can convert a
Path into a string and get pretty much what you would expect:
>>> str(p.parent) '/path/to/my'
And also on any
Path you can use the
.absolute() method to get an absolute path:
>>> os.chdir('/etc') >>> p = pathlib.Path('../relative/path') >>> str(p.parent) '../relative' >>> str(p.parent.absolute()) '/etc/../relative'
pathlib treat paths with a trailing slash differently. The
pathlib parent of
>>> p = pathlib.Path('some/path/') >>> p.parent PosixPath('some')
>>> os.path.dirname('some/path/') 'some/path'
This question is answered By – larsks
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0