Search code examples
pythonpython-importrelative-path

Confused about using relative and absolute path in Python


I have a script called "test.py" and refers to a config file called "cfg.yaml". These two reside in the same directory called "test/scripts".

test/scripts/test.py
test/script/cfg.yaml

Now I am writing a bash script inside "test/data1/data2" called task.sh

From inside of task.sh, I want to make a call to the python script

test.sh contents are as below:

#!/bin/sh

python ../../scripts/test.py

test.py opens and reads the cfg.yaml like open("cfg.yaml") but when the test.sh is called, it fails because "cfg.yaml" is NOT referred with relative path. How do I resolve this?


Solution

  • try

    #!/bin/sh
    
    cd ../../scripts
    python test.py
    

    I assume in test.py you are referencing the yaml with a local path that expects the script to be running from the scripts directory (not from data1/data2)

    as an aside you can always print os.getcwd() to see what your working directory is while running the python script (or just pwd in bash)