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?
import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
This worked for me (I am on Ubuntu):
import os
os.path.dirname(os.getcwd())
'..'
returns parent of current directory.
import os
os.chdir('..')
Now your current directory will be /home/kristina/desire-directory
.
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())
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
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])
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)
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
Source: Stackoverflow.com