Search code examples
pythonpython-3.4cd

Running python codes from outside the directory when script has filepaths


So I have a python script my_script.py which is inside the folder Test and I am outside this folder. The script requires to access some input data from the file my_data.dat stored inside the folder Test.

Now, when I try to run this script from outside the folder Test, using simple python my_script.py, it tries to locate my_data.dat in the folder from which I am running the script and so fails. How can I tell it use the correct path without actually modifying the path in the my_script.py?

I don't want to modify the paths in the script because the script is to be used generically for various paths and the whole thing would be automated later.


Solution

  • You need to use absolute file path instead of the relative file path.

    To get absolute path of directory containing python file:

    import os
    ROOT_DIR = os.path.dirname(__file__)
    

    And you can get absolute path of my_data.dat

    data_file_path = os.path.join(ROOT_DIR, 'my_data.dat')
    

    Afterward use data_file_path instead of "my_data.dat"