Fedorenko Kristina Fedorenko Kristina - 7 months ago 72
Python Question

Get parent of current directory from Python script

I want to get the parent of current directory from Python script. For example I launch the script from

the desire path in this case is

I know
. But I don't want to parse
resulting string. Is there any another way to get parent of current directory in Python?


Yes, you can walk up the directory tree using os.path.dirname:

In [4]: from os.path import dirname

In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'

In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'

Inside the script pass os.path.abspath(__file__) to os.path.dirname:

from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory

Another option is the pathlib module (available in Python 3.4 or newer). Each pathlib.Path instance have the parent attribute that refers to the parent directory:

In [11]: from pathlib import Path

In [12]: script = Path('/home/kristina/desire-directory/scripts/script.py')

In [13]: script.parent
Out[13]: PosixPath('/home/kristina/desire-directory/scripts')

In [14]: script.parent.parent
Out[14]: PosixPath('/home/kristina/desire-directory')

Note that Path.parent is a Path instance, which isn't always handy. You can convert it to str:

In [15]: str(script.parent.parent)
Out[15]: '/home/kristina/desire-directory'

Path.resolve may be used to obtain the absolute path (it also resolves symlinks):

from pathlib import Path
d = str(Path(__file__).resolve().parent.parent) # '/home/kristina/desire-directory'