This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: get the nth folder of a given path
Type: enhancement Stage: resolved
Components: Versions:
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: Nosy List: amjad ben hedhili, eric.smith, serhiy.storchaka, taleinat
Priority: normal Keywords:

Created on 2018-03-19 13:25 by amjad ben hedhili, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (6)
msg314094 - (view) Author: AmjadHD (amjad ben hedhili) Date: 2018-03-19 13:25
It will be handy if there was an os or os.path function that returns the path to the nth directory in a given path

for example:
given path = "C:\Users\User\AppData\Local\Programs\Python\Python36\Lib\asyncio\__init__.py"

os.path.nthpath(path, 2) returns "C:\Users\User\AppData\Local\Programs\Python\Python36\Lib"
msg314096 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2018-03-19 13:57
Path.parents will do what you want. I don't have a Windows box handy, but this is on MacOS:

>>> from pathlib import Path
>>> p = Path("/Users/User/AppData/Local/Programs/Python/Python36/Lib/asyncio/__init__.py")
>>> p.parents[1]
PosixPath('/Users/User/AppData/Local/Programs/Python/Python36/Lib')
>>>
msg314199 - (view) Author: AmjadHD (amjad ben hedhili) Date: 2018-03-21 14:41
Yes but i dont know if this is cross platform solution, i guess this function should be in the os.path module.
msg314200 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2018-03-21 14:51
Yes, it's cross platform.

For a plain string version, you can use a utility function:

>>> for i in range(n+1):
...   path = os.path.dirname(path)
...

I'm not sure it's worth adding this to os.path.
msg322376 - (view) Author: Tal Einat (taleinat) * (Python committer) Date: 2018-07-25 17:47
-1 on adding this to os.path given the existence in pathlib.
msg322384 - (view) Author: Tal Einat (taleinat) * (Python committer) Date: 2018-07-25 18:44
I'm closing this as "wontfix".

Amjad, if you'd like to discuss this further, please bring it up on python-ideas.

Serhiy, as the expert for the os.path module, FYI.
History
Date User Action Args
2022-04-11 14:58:58adminsetgithub: 77283
2018-07-25 18:44:42taleinatsetstatus: open -> closed
resolution: wont fix
stage: resolved
2018-07-25 18:44:23taleinatsetnosy: + serhiy.storchaka
messages: + msg322384
2018-07-25 17:47:41taleinatsetnosy: + taleinat
messages: + msg322376
2018-03-21 14:51:24eric.smithsetmessages: + msg314200
2018-03-21 14:41:23amjad ben hedhilisetmessages: + msg314199
2018-03-19 13:57:14eric.smithsetnosy: + eric.smith
messages: + msg314096
2018-03-19 13:26:58amjad ben hedhilisettitle: get the nth folder -> get the nth folder of a given path
2018-03-19 13:25:56amjad ben hedhilicreate