Reputation: 430
I'm trying to run python file by from different directory, but I want that directory to be current work directory.
For ex Let's say below is my project structure
project_name/core/main.py
project_name/core/app1.py
project_name/core/app2.py
project_name/log/log.txt
project_name/config/userconfig/user.json
project_name/config/systemconfig/system.json
cmd
at project_name directory, where I can run main.py
using this command python core/main.py
Now I if want to access user.json
from I have to give path that config/userconfig/user.json
in the code
cmd
at core folder and I can run command that python main.py
Now I if want to access user.json
from I have to give path that ../config/userconfig/user.json
in the code
So when I have to give path according to from where I'm running the code, how can I make my code always works regardless of from where I'm running my python code.
Upvotes: 1
Views: 59
Reputation: 107095
You can use the __file__
variable to obtain the full pathname of main.py
, get its directory path with os.path.dirname
, and then join it with the relative path to the config file:
os.path.join(os.path.dirname(__file__), '..', 'config', 'userconfig', 'user.json')
Upvotes: 2
Reputation: 23
I guess you could try to use absolute paths. E.g. C:/your/absolute/path/.../project_name/config/userconfig/user.json
Upvotes: 0