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
I use the following apprach.
(a) Split the full path to the file by the os spearator.
(b) Take the resulting array and return the elments with indexes ranging from [0: lastIndex-1] - In short, remove the last element from the array that results from the split
(c) SImply join together the array that is one elment short using the os separator once again. Should work for windows and linux.
Here is a class function exemplifying.
# @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