Get parent of current directory from Python script
Asked Answered
F

10

105

I want to get the parent of current directory from Python script. For example I launch the script from /home/kristina/desire-directory/scripts the desire path in this case is /home/kristina/desire-directory

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

Finnish answered 13/5, 2015 at 15:7 Comment(0)
P
204

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, abspath
d = 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 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'

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

import os
d = 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 Path
d = 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'
Pooley answered 13/5, 2015 at 15:8 Comment(4)
Path(__file__).resolve().parent -> Path(".").resolve(). This also works when there isn't a __file__ because you started in the interactive interpreter.Shire
if script is in /scripts folder, like` /home/kristina/desire-directory/scripts/myScript.py` the first solution will not return the desired directory, it will return /scripts insteadHali
all others os.blabla isn't work for me but this solution. Many many thanks!Geist
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent, this works for meMetzger
R
25

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
Roxannaroxanne answered 21/9, 2016 at 13:33 Comment(0)
C
14

This worked for me (I am on Ubuntu):

import os
os.path.dirname(os.getcwd())
Crine answered 29/4, 2016 at 13:10 Comment(0)
S
8
import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
Sandfly answered 13/5, 2015 at 15:51 Comment(0)
W
1

For me, this is what worked:

from os import path
path.dirname(path.dirname(__file__))

You get the current directory using the current file as a reference, and then call the path.dirname again to get the parent directory.

Warsle answered 7/6, 2022 at 13:54 Comment(0)
H
0

'..' returns parent of current directory.

import os
os.chdir('..')

Now your current directory will be /home/kristina/desire-directory.

Heinrick answered 14/11, 2018 at 11:8 Comment(0)
G
0

You can simply use../your_script_name.py For example suppose the path to your python script is trading system/trading strategies/ts1.py. To refer to volume.csv located in trading system/data/. You simply need to refer to it as ../data/volume.csv

Guidepost answered 9/3, 2019 at 2:4 Comment(0)
F
0

import os def parent_directory(): # Create a relative path to the parent # of the current working directory path = os.getcwd() parent = os.path.dirname(path)

relative_parent = os.path.join(path, parent)

# Return the absolute path of the parent directory
return relative_parent

print(parent_directory())

Frazil answered 3/8, 2020 at 9:54 Comment(0)
P
0
import os
import sys
from os.path import dirname, abspath

d = dirname(dirname(abspath(__file__)))
print(d)
path1 = os.path.dirname(os.path.realpath(sys.argv[0]))
print(path1)
path = os.path.split(os.path.realpath(__file__))[0]
print(path)
Paramagnetism answered 4/12, 2020 at 2:15 Comment(0)
P
-1
from os.path import dirname
from os.path import abspath

def get_file_parent_dir_path():
    """return the path of the parent directory of current file's directory """
    current_dir_path = dirname(abspath(__file__))
    path_sep = os.path.sep
    components = current_dir_path.split(path_sep)
    return path_sep.join(components[:-1])
Pasia answered 10/3, 2016 at 16:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.