Reputation: 950
Let's say I have the current file structure :
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 :
"modules\\somefile.txt"
"..\\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 ?
Upvotes: 4
Views: 1474
Reputation: 123463
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")
Upvotes: 5