pythonfilenamespython-ospathlib

How to get folder name, in which given file resides, from pathlib.path?


Is there something similar to os.path.dirname(path), but in pathlib?


Solution

  • 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')
    

    Then p.parents[0] is the directory containing file:

    >>> p.parents[0]
    PosixPath('/path/to/my')
    

    ...and p.parents[1] will be the next directory up:

    >>> p.parents[1]
    PosixPath('/path/to')
    

    Etc.

    p.parent is another way to ask for p.parents[0]. 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'