Get parent of current directory from Python script Get parent of current directory from Python script python python

Get parent of current directory from Python script


Using os.path

To get the parent directory of the directory containing the script (regardless of the current working directory), you'll need to use __file__.

Inside the script use os.path.abspath(__file__) to obtain the absolute path of the script, and call os.path.dirname twice:

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

Basically, you can walk up the directory tree by calling os.path.dirname as many times as needed. Example:

In [4]: from os.path import dirnameIn [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'

If you want to get the parent directory of the current working directory, use os.getcwd:

import osd = os.path.dirname(os.getcwd())

Using pathlib

You could also use the pathlib module (available in Python 3.4 or newer).

Each pathlib.Path instance have the parent attribute referring to the parent directory, as well as the parents attribute, which is a list of ancestors of the path. Path.resolve may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absolute instead if that isn't a desired behaviour.

Path(__file__) and Path() represent the script path and the current working directory respectively, therefore in order to get the parent directory of the script directory (regardless of the current working directory) you would use

from pathlib import Path# `path.parents[1]` is the same as `path.parent.parent`d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')

and to get the parent directory of the current working directory

from pathlib import Pathd = Path().resolve().parent

Note that d is a Path instance, which isn't always handy. You can convert it to str easily when you need it:

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


Use Path.parent from the pathlib module:

from pathlib import Path# ...Path(__file__).parent

You can use multiple calls to parent to go further in the path:

Path(__file__).parent.parent


This worked for me (I am on Ubuntu):

import osos.path.dirname(os.getcwd())