tags:

views:

153

answers:

5

Hi,

Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g.

C:\Program Files ---> C:\

and

C:\ ---> C:\

If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google.

Thanks.

A: 
os.path.abspath(os.path.join(somepath, '..'))

Observe:

import posixpath
import ntpath

print ntpath.abspath(ntpath.join('C:\\', '..'))
print ntpath.abspath(ntpath.join('C:\\foo', '..'))
print posixpath.abspath(posixpath.join('/', '..'))
print posixpath.abspath(posixpath.join('/home', '..'))
Ignacio Vazquez-Abrams
A: 
os.path.split(os.path.abspath(dir))[0]
Dan Menes
+1  A: 

Try this:

import os.path
print os.path.abspath(os.path.join(yourpath, '..'))

where yourpath is the path you want the parent for.

kender
Your answer is correct but convoluted; `os.path.dirname` is the function for this, like `a+=5-4` is more convoluted than `a+=1`. The question requested only the parent directory, not whether is exists or the *true* parent directory assuming symbolic links get in the way.
ΤΖΩΤΖΙΟΥ
A: 
import os
p = os.path.abspath('..')

C:\Program Files ---> C:\\

C:\ ---> C:\\

ivo
+1  A: 

os.path.dirname

>>> os.path.dirname(r'C:\Program Files')
'C:\\'
>>> os.path.dirname('C:\\')
'C:\\'
>>>
Wai Yip Tung
`os.path.dirname(r'C:\Program Files')` what? Python's just giving you the directory where the file 'Program Files' would be. What's more, it doesn't even have to exist, behold: `os.path.dirname(r'c:\i\like\to\eat\pie')` outputs `'c:\\i\\like\\to\\eat'`
Nick T
The original poster does not state that the directory have to exist. There are a lot of pathname methods that does nothing but string manipulation. To verify if the pathname actually exist requires a disk access. Depends on the application this may or may not be desirable.
Wai Yip Tung
Seems that this would be a good solution if you knew that the input directory was valid (which can be checked).
Jeff