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"
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') >>>
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.
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:58
admin
set
github: 77283
2018-07-25 18:44:42
taleinat
set
status: open -> closedresolution: wont fixstage: resolved