Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a file's parent directory?

Given a path to a file, c:\xxx\abc\xyz\fileName.jpg, how can I get the file's parent folder? In this example, I'm looking for xyz. The number of directories to get to the file may vary.

like image 512
DenaliHardtail Avatar asked Jul 20 '15 20:07

DenaliHardtail


2 Answers

Using python >= 3.4 pathlib is part of the standard library, you can get the parent name with .parent.name:

from pathlib import Path
print(Path(path).parent.name)

To get all the names use .parents:

print([p.name for p in Path(path).parents])

It can be installed for python2 with pip install pathlib

like image 145
Padraic Cunningham Avatar answered Sep 17 '22 00:09

Padraic Cunningham


Use os.path.dirname to get the directory path. If you only want the name of the directory, you can use os.path.basename to extract the base name from it:

>>> path = r'c:\xxx\abc\xyz\fileName.jpg'
>>> import os
>>> os.path.dirname(path)
'c:\\xxx\\abc\\xyz'
>>> os.path.basename(os.path.dirname(path))
'xyz'
like image 41
poke Avatar answered Sep 20 '22 00:09

poke