Referring to the question here Relative paths in Python. I have similar problem to that.
My project structure:
proj
|
|--config
| |--ENV
|
|--folder1
| |--UI
| |--test2.py
|
|--test1.py
I want to access the ENV file using test1.py and test2.py but I was to use relative address so that I don't have to change the code every time I move my project.
import inspect
import os
dirname = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
filename = os.path.join(dirname, 'config/ENV')
code above works fine at test1.py but fails at test2.py because now dirname
is changed.
I am looking code that I can use on both file. Currently I only have one idea is to split the address on the basis of \
find proj
and append config/ENV
is there any better and cleaner way to do it?
C:\Users\User1\proj\config/ENV -- at test1.py
C:\Users\User1\proj\folder1\UI\config/ENV -- at test2.py
My Current solution:
dirname = os.path.dirname(__file__)
PROJECT_NAME = "proj"
x = dirname[:dirname.find(PROJECT_NAME) + len(PROJECT_NAME)]
filename = os.path.join(x, 'config/ENV')