Peaceful
Peaceful

Reputation: 5480

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.

Upvotes: 0

Views: 835

Answers (2)

cco
cco

Reputation: 6301

You can either pass the path to my_data.dat as a parameter to the script, or (if the data file is always in the same directory as the script) you can use the variable __file__ to determine where the script is and look for the data file in that directory.

Upvotes: 0

Adnan Umer
Adnan Umer

Reputation: 3689

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"

Upvotes: 1

Related Questions