16

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.

asked Jul 20, 2015 at 20:24

4 Answers 4

21

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'
answered Jul 20, 2015 at 20:27
Sign up to request clarification or add additional context in comments.

Comments

8

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

answered Jul 20, 2015 at 20:52

Comments

0

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
answered Jul 19, 2017 at 12:01

Comments

-2

If all your paths look the same like the one you provided:

print path.split('\\')[-2]
answered Jul 20, 2015 at 20:26

2 Comments

This won't work on other OS. It's base idea to hard code path separator in code.
@ShitalShah I agree that this nearly 4 year old answer was not perfect, but OP had specific paths (with given path separators!) so the answer was simple and would work for him. Your comment was unnecessary and the downvote too.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.