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


I need to extract the name of the parent directory of a certain path. This is what it looks like:


I would like to extract directory_i_need.

Answer rating: 273

import os
## first file in current dir (with full path)
file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
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 you"re 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.

Answer rating: 62

For Python 3.4+, try the pathlib module:

>>> from pathlib import Path

>>> p = Path("C:Program FilesInternet Exploreriexplore.exe")

>>> str(p.parent)
"C:Program FilesInternet Explorer"

>>> p.name

>>> p.suffix

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

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

>>> p.exists()

Get Solution for free from DataCamp guru