This morning I was trying to find a good way of using os.path to load the content of a text file into memory, which exists in the root directory of my current project.
This approach strikes me as a bit hackneyed, but after some thought it was exactly what I was about to do, except with os.path.normpath(os.path.join(__file__, '..', '..'))
These relative operations on the path to navigate to a static root directory are brittle.
Now, if my project layout changes, these associations to the (former) root directory change with it. I wish I could assign the path to find a target, or a destination, instead of following a sequence of navigation operations.
I was thinking of making a special __root__.py file. Does this look familiar to anyone, or know of a better implementation?
my_project
|
| __init__.py
| README.md
| license.txt
| __root__.py
| special_resource.txt
| ./module
|-- load.py
Here is how it is implemented:
"""__root__.py"""
import os
def path():
return os.path.dirname(__file__)
And here is how it could be used:
"""load.py"""
import __root__
def resource():
return open(os.path.join(__root__.path(), 'special_resource.txt'))