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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Python 3.4
Use the pathlib module.
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent.absolute())
Old answer
Try this:
import os print os.path.abspath(os.path.join(yourpath, os.pardir))
where yourpath is the path you want the parent for.
Method 2
Using os.path.dirname:
>>> os.path.dirname(r'C:Program Files')
'C:\'
>>> os.path.dirname('C:\')
'C:\'
>>>
Caveat: os.path.dirname() gives different results depending on whether a trailing slash is included in the path. This may or may not be the semantics you want. Cf. @kender’s answer using os.path.join(yourpath, os.pardir).
Method 3
The Pathlib method (Python 3.4+)
from pathlib import Path
Path('C:Program Files').parent
# Returns a Pathlib object
The traditional method
import os.path
os.path.dirname('C:Program Files')
# Returns a string
Which method should I use?
Use the traditional method if:
- You are worried about existing code generating errors if it were to use a Pathlib object. (Since Pathlib objects cannot be concatenated with strings.)
- Your Python version is less than 3.4.
- You need a string, and you received a string. Say for example you have a string representing a filepath, and you want to get the parent directory so you can put it in a JSON string. It would be kind of silly to convert to a Pathlib object and back again for that.
If none of the above apply, use Pathlib.
What is Pathlib?
If you don’t know what Pathlib is, the Pathlib module is a terrific module that makes working with files even easier for you. Most if not all of the built in Python modules that work with files will accept both Pathlib objects and strings. I’ve highlighted below a couple of examples from the Pathlib documentation that showcase some of the neat things you can do with Pathlib.
Navigating inside a directory tree:
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.resolve" rel="nofollow noreferrer noopener">q.resolve()</a>
PosixPath('/etc/rc.d/init.d/halt')
Querying path properties:
>>> <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.exists" rel="nofollow noreferrer noopener">q.exists()</a> True >>> <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_dir" rel="nofollow noreferrer noopener">q.is_dir()</a> False
Method 4
import os
p = os.path.abspath('..')
C:Program Files —> C:\
C: —> C:\
Method 5
An alternate solution of @kender
import os os.path.dirname(os.path.normpath(yourpath))
where yourpath is the path you want the parent for.
But this solution is not perfect, since it will not handle the case where yourpath is an empty string, or a dot.
This other solution will handle more nicely this corner case:
import os os.path.normpath(os.path.join(yourpath, os.pardir))
Here the outputs for every case that can find (Input path is relative):
os.path.dirname(os.path.normpath('a/b/')) => 'a'
os.path.normpath(os.path.join('a/b/', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/b')) => 'a'
os.path.normpath(os.path.join('a/b', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/')) => ''
os.path.normpath(os.path.join('a/', os.pardir)) => '.'
os.path.dirname(os.path.normpath('a')) => ''
os.path.normpath(os.path.join('a', os.pardir)) => '.'
os.path.dirname(os.path.normpath('.')) => ''
os.path.normpath(os.path.join('.', os.pardir)) => '..'
os.path.dirname(os.path.normpath('')) => ''
os.path.normpath(os.path.join('', os.pardir)) => '..'
os.path.dirname(os.path.normpath('..')) => ''
os.path.normpath(os.path.join('..', os.pardir)) => '../..'
Input path is absolute (Linux path):
os.path.dirname(os.path.normpath('/a/b')) => '/a'
os.path.normpath(os.path.join('/a/b', os.pardir)) => '/a'
os.path.dirname(os.path.normpath('/a')) => '/'
os.path.normpath(os.path.join('/a', os.pardir)) => '/'
os.path.dirname(os.path.normpath('/')) => '/'
os.path.normpath(os.path.join('/', os.pardir)) => '/'
Method 6
os.path.split(os.path.abspath(mydir))[0]
Method 7
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', '..'))
Method 8
import os
print"------------------------------------------------------------"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
print("example 1: "+SITE_ROOT)
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
print("example 2: "+PARENT_ROOT)
GRANDPAPA_ROOT=os.path.abspath(os.path.join(PARENT_ROOT, os.pardir))
print("example 3: "+GRANDPAPA_ROOT)
print "------------------------------------------------------------"
Method 9
>>> import os >>> os.path.basename(os.path.dirname(<your_path>))
For example in Ubuntu:
>>> my_path = '/home/user/documents' >>> os.path.basename(os.path.dirname(my_path)) # Output: 'user'
For example in Windows:
>>> my_path = 'C:WINDOWSsystem32' >>> os.path.basename(os.path.dirname(my_path)) # Output: 'WINDOWS'
Both examples tried in Python 2.7
Method 10
Suppose we have directory structure like
1]
/home/User/P/Q/R
We want to access the path of “P” from the directory R then we can access using
ROOT = os.path.abspath(os.path.join("..", os.pardir));
2]
/home/User/P/Q/R
We want to access the path of “Q” directory from the directory R then we can access using
ROOT = os.path.abspath(os.path.join(".", os.pardir));
Method 11
If you want only the name of the folder that is the immediate parent of the file provided as an argument and not the absolute path to that file:
os.path.split(os.path.dirname(currentDir))[1]
i.e. with a currentDir value of /home/user/path/to/myfile/file.ext
The above command will return:
myfile
Method 12
import os dir_path = os.path.dirname(os.path.realpath(__file__)) parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))
Method 13
import os.path os.path.abspath(os.pardir)
Method 14
print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))
You can use this to get the parent directory of the current location of your py file.
Method 15
Just adding something to the Tung’s answer (you need to use rstrip('/') to be more of the safer side if you’re on a unix box).
>>> input = "../data/replies/"
>>> os.path.dirname(input.rstrip('/'))
'../data'
>>> input = "../data/replies"
>>> os.path.dirname(input.rstrip('/'))
'../data'
But, if you don’t use rstrip('/'), given your input is
>>> input = "../data/replies/"
would output,
>>> os.path.dirname(input) '../data/replies'
which is probably not what you’re looking at as you want both "../data/replies/" and "../data/replies" to behave the same way.
Method 16
GET Parent Directory Path and make New directory (name new_dir)
Get Parent Directory Path
os.path.abspath('..')
os.pardir
Example 1
import os print os.makedirs(os.path.join(os.path.dirname(__file__), os.pardir, 'new_dir'))
Example 2
import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.path.abspath('..'), 'new_dir'))
Method 17
os.path.abspath('D:Dir1Dir2..')
>>> 'D:Dir1'
So a .. helps
Method 18
import os
def parent_filedir(n):
return parent_filedir_iter(n, os.path.dirname(__file__))
def parent_filedir_iter(n, path):
n = int(n)
if n <= 1:
return path
return parent_filedir_iter(n - 1, os.path.dirname(path))
test_dir = os.path.abspath(parent_filedir(2))
Method 19
The answers given above are all perfectly fine for going up one or two directory levels, but they may get a bit cumbersome if one needs to traverse the directory tree by many levels (say, 5 or 10). This can be done concisely by joining a list of N os.pardirs in os.path.join. Example:
import os # Create list of ".." times 5 upup = [os.pardir]*5 # Extract list as arguments of join() go_upup = os.path.join(*upup) # Get abspath for current file up_dir = os.path.abspath(os.path.join(__file__, go_upup))
Method 20
To find the parent of the current working directory:
import pathlib pathlib.Path().resolve().parent
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0