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

PythonDirectoryFilepath

Python Problem Overview


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

C:\stuff\directory_i_need\subdir\file.jpg

I would like to extract directory_i_need.

Python Solutions


Solution 1 - 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 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.

Solution 2 - Python

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

Solution 3 - Python

All you need is parent part if you use [pathlib][1].

from pathlib import Path
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parent) 

Will output:

C:\Program Files\Internet Explorer    

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

p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parts) 

Then you will get a list:

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

Saves tone of time. [1]: https://docs.python.org/3/library/pathlib.html

Solution 4 - Python

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:\mystuff\project\file.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.

Solution 5 - Python

import os

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

directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:\Users\User\Desktop'

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.

Solution 6 - Python

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.

Solution 7 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThaliaView Question on Stackoverflow
Solution 1 - PythonNisan.HView Answer on Stackoverflow
Solution 2 - PythonNoam ManosView Answer on Stackoverflow
Solution 3 - PythonprostiView Answer on Stackoverflow
Solution 4 - PythonelyView Answer on Stackoverflow
Solution 5 - PythonBasti WürzburgView Answer on Stackoverflow
Solution 6 - PythonThaliaView Answer on Stackoverflow
Solution 7 - PythonKeithView Answer on Stackoverflow