Is there something similar to os.path.dirname(path)
, but in pathlib?
Python – How to Get Folder Name from pathlib.path
filenamespathlibpythonpython-os
Related Question
- Python Pandas – How to Iterate Over Rows in a DataFrame
- Python Random List – How to Randomly Select an Item from a List
- Python Dictionary Sorting – How to Sort by Value
- Python – How to Split the Definition of a Long String Over Multiple Lines
- Python – Extract File Name from Path Across OS Formats
- Python Performance – Why ‘1000000000000000 in range(1000000000000001)’ is So Fast in Python 3
Best Answer
It looks like there is a
parents
element that contains all the parent directories of a given path. E.g., if you start with:Then
p.parents[0]
is the directory containingfile
:...and
p.parents[1]
will be the next directory up:Etc.
p.parent
is another way to ask forp.parents[0]
. You can convert aPath
into a string and get pretty much what you would expect:And also on any
Path
you can use the.absolute()
method to get an absolute path: