Extract a part of the filepath (a directory) in Python

Extract a part of the filepath (a directory) in Python

import os
## first file in current dir (with full path)
file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
file
os.path.dirname(file) ## directory of file
os.path.dirname(os.path.dirname(file)) ## directory of directory of file
...

And you can continue doing this as many times as necessary…

Edit: from os.path, you can use either os.path.split or os.path.basename:

dir = os.path.dirname(os.path.dirname(file)) ## dir of dir of file
## once youre at the directory level you want, with the desired directory as the final path node:
dirname1 = os.path.basename(dir) 
dirname2 = os.path.split(dir)[1] ## if you look at the documentation, this is exactly what os.path.basename does.

For Python 3.4+, try the pathlib module:

>>> from pathlib import Path

>>> p = Path(C:\Program Files\Internet Explorer\iexplore.exe)

>>> str(p.parent)
C:\Program Files\Internet Explorer

>>> p.name
iexplore.exe

>>> p.suffix
.exe

>>> p.parts
(C:\, Program Files, Internet Explorer, iexplore.exe)

>>> p.relative_to(C:\Program Files)
WindowsPath(Internet Explorer/iexplore.exe)

>>> p.exists()
True

Extract a part of the filepath (a directory) in Python

All you need is parent part if you use pathlib.

from pathlib import Path
p = Path(rC:Program FilesInternet Exploreriexplore.exe)
print(p.parent) 

Will output:

C:Program FilesInternet Explorer    

Case you need all parts (already covered in other answers) use parts:

p = Path(rC:Program FilesInternet Exploreriexplore.exe)
print(p.parts) 

Then you will get a list:

(C:\, Program Files, Internet Explorer, iexplore.exe)

Saves tone of time.

Leave a Reply

Your email address will not be published. Required fields are marked *