问题
Let's say I have the current file structure :
- app\modules\module.py
- app\modules\somefile.txt
- app\scripts\script.py
- app\main.py
modules\script.py :
import sys
sys.path.append("..\\")
from modules.module import module
[...]
main.py :
import sys
from modules.module import module
[...]
modules\module.py :
[...]
fileToRead="somefile.txt"
The problem is :
- If my module is imported from main.py, the path to somefile.txt should be
"modules\\somefile.txt" - If my module is imported from script.py, the path to somefile.txt should be
"..\\modules\\somefile.txt"
I don't want to use an absolute path as I want my app folder to be movable. I thought of a path relative to the root folder, but I don't know if it's a clean solution and I don't want to pollute all my scripts with redondant stuff.
Is there a clean way to deal with this ?
回答1:
I'm not sure what all you're doing, but since somefile.txt is in the same folder as module.py, you could make the path to it relative to the module by using its predefined __file__ attribute:
import os
fileToRead = os.path.join(os.path.dirname(__file__), "somefile.txt")
来源:https://stackoverflow.com/questions/30508146/having-a-relative-path-in-a-module-relative-to-the-file-calling-the-module