close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get folder name, in which given file resides, from pathlib.path in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

  1. 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:

  2. 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:

Method 1

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'

Note that os.path.dirname and pathlib treat paths with a trailing slash differently. The pathlib parent of some/path/ is some:

>>> p = pathlib.Path('some/path/')
>>> p.parent
PosixPath('some')

While os.path.dirname on some/path/ returns some/path:

>>> os.path.dirname('some/path/')
'some/path'

Method 2

I came here looking for something very similar. My solution, based on the above by @larsks, and assuming you want to preserve the entire path except the filename, is to do:

>>> import pathlib
>>> p = pathlib.Path('/path/to/my/file')
>>> pathlib.Path('/'.join(list(p.parts)[1:-1])+'/')

Essentially, list(p.parts)[1:-1] creates a list of Path elements, starting from the second to n-1th, and you join them with a ‘/’ and make a path of the resulting string. Edit The final +’/’ adds in the trailing slash – adjust as required.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read