How do I get the parent directory of a file?

Given the file path, c:\xxx\abc\xyz\fileName.jpg

how can I get the parent folder of the file? In this example, I am looking for xyz

. The number of directories to access the file can vary.

+3


source to share


4 answers


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'

      

+4


source


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

+1


source


If all your paths look the same as the ones you provided:

print path.split('\\')[-2]

      

0


source


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

      

0


source







All Articles