In several SO's question there is these lines to access the parent directory of the code, e.g. os.path.join(os.path.dirname(__file__)) returns nothing and os.path.join(os.path.dirname(__file__)) returns nothing
import os, sys
parentddir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
sys.path.append(parentddir)
I understand that os.path.abspath()
returns absolute path of something and sys.path.append()
adds the path for the code to access. but what is this cryptic line below, what does it really mean?
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
Is there another way to achieve the same purpose of appending the parent directory of the where the code?
This problem happens because I am calling functions across directories and sometimes they share the same file name, e.g. script1/utils.py
and script2/utils.py
. I am calling a function from script1/test.py
which calls script2/something.py
contains a function that calls script2/utils.py
and the following code
script1/
utils.py
src/
test.py
script2/
utils.py
code/
something.py
test.py
from script2.code import something
import sys
sys.path.append('../')
import utils
something.foobar()
something.py
import os, sys
parentddir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
sys.path.append(parentddir)
import utils
def foobar():
utils.somefunc()