For example:

mypath = "C:\\some_folder\\some_subfolder" 

How to get the parent directory on this path? Of course it is possible

 parent = os.path.abspath(os.path.join(mypath, '..')) 

but this way seems to me somehow clumsy, like

 parent = os.sep.join(os.path.split(mypath)[:-1]) 

    2 answers 2

    The result of os.path.dirname() depends on the presence of a slash at the end of the path:

     >>> os.path.dirname('/a/b') '/a' >>> os.path.dirname('/a/b/') '/a/b' 

    If this is not desirable, then you can use the answer @kender to the question "How do I get the parent directory in Python?" :

     >>> parent_dir = lambda path: os.path.abspath(os.path.join(path, os.pardir)) >>> parent_dir('/a/b') '/a' >>> parent_dir('/a/b/') '/a' 

    pathlib.Path.parent attribute behaves like:

     >>> from pathlib import Path >>> Path('/a/b').parent PosixPath('/a') >>> Path('/a/b/').parent PosixPath('/a') 

    If there may be symbolic links in the path or the presence of '..' ( os.pardir ) is already present, then depending on the desired result, you may also need os.path.realpath(path_with_symlink) , os.path.abspath(path_with_dots) or pathlib.Path.resolve() call.

    • Perhaps os.path.abspath(os.path.join(path, os.pardir)) I like more. By the way, with .. on the way he copes perfectly. Along the way, the question is why os.listdir(path) does not issue .. (in Windows at least)? - andy.37
    • @ andy.37 With .. in the way the normpath() function is called, called abspath() . About listdir() and '..' it is better to ask a separate question (I assume '.' , And '..' not shown, because they are in every directory and always mean the same thing as a rule). - jfs

    You can use os.path.dirname('path') . If you need a directory even lower, transfer the resulting value further.
    Here, for example, settings from the Django project

     BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) >>> BASE_DIR '/home/user/projects/myproject' >>> os.path.dirname(BASE_DIR) '/home/user/projects' 
    • Thank. As I did not find the obvious)) I’m listdir with django, it took listdir , but the listdir .. does not give out. - andy.37
    • @ andy.37 please - Ivan Semochkin
    • python.org/dev/peps/pep-0471 scandir (path = '.') -> generator of DirEntry objects - vadim vaduxa