How do I get the parent directory of a file?
Use os.path.dirname
to get the path to the directory. 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'
source to share
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 use all names, use .parents:
print([p.name for p in Path(path).parents])
It can be installed python2
withpip install pathlib
source to share
I am using the following estimate.
(a) Split the full path to the file using os spearator.
(b) Take the resulting array and return elements with indices in the range [0: lastIndex-1] - In short, remove the last element from the array that is obtained from split
(c) SImply concatenates the array that is one of the red words using the os separator again. Should work for windows and Linux.
Here is an example of a class function.
# @param
# absolutePathToFile an absolute path pointing to a file or directory
# @return
# The path to the parent element of the path (e.g. if the absolutePathToFile represents a file, the result is its parent directory)
# if the path represent a directory, the result is its parent directory
def getParentDirectoryFromFile(self, absolutePathToFile):
splitResutsFromZeroToNMinus1 = absolutePathToFile.split(os.sep)[:-1]
return os.sep.join(splitResutsFromZeroToNMinus1)
pass
source to share