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

Question:

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

C:stuffdirectory_i_needsubdirfile.jpg

I would like to extract directory_i_need.

Asked By: Thalia

||

Answers:

You have to put the entire path as a parameter to os.path.split. See The docs. It doesn’t work like string split.

Answered By: Keith

First, see if you have splitunc() as an available function within os.path. The first item returned should be what you want… but I am on Linux and I do not have this function when I import os and try to use it.

Otherwise, one semi-ugly way that gets the job done is to use:

>>> pathname = "\C:\mystuff\project\file.py"
>>> pathname
'\C:\mystuff\project\file.py'
>>> print pathname
C:mystuffprojectfile.py
>>> "\".join(pathname.split('\')[:-2])
'\C:\mystuff'
>>> "\".join(pathname.split('\')[:-1])
'\C:\mystuff\project'

which shows retrieving the directory just above the file, and the directory just above that.

Answered By: ely
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 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.
Answered By: Nisan.H

This is what I did to extract the piece of the directory:

for path in file_list:
  directories = path.rsplit('\')
  directories.reverse()
  line_replace_add_directory = line_replace+directories[2]

Thank you for your help.

Answered By: Thalia

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
Answered By: Noam Manos

All you need is parent part if you use pathlib.

from pathlib import Path
p = Path(r'C: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(r'C:Program FilesInternet Exploreriexplore.exe')
print(p.parts) 

Then you will get a list:

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

Saves tone of time.

Answered By: prosti
import os

directory = os.path.abspath('\') # root directory
print(directory) # e.g. 'C:'

directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:UsersUserDesktop'

parent_directory, directory_name = os.path.split(directory)
print(directory_name) # e.g. 'Desktop'
parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
print(parent_directory_name) # e.g. 'User'

This should also do the trick.

Answered By: Basti Würzburg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.