Reputation: 1463
Is there a way to find out the path of a current project in a subfolder?
If I have for instance something like:
/
main.py
/utils
utilities.py
/foo
foo.py
/foo/bar
bar.py
While coding in /foo/foo.py
or in /foo/bar/bar.py
I want to include the "utilities" module located at /utils/utilities.py
How can I do this by calling some sort of relative path to the project and then just import this helper module?
I am able to retrieve the path of a file being executed with:
os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
But what I need is the relative or absolute path of the current project.
Thanks in advance.
Upvotes: 1
Views: 2081
Reputation: 1463
I got this working with an example provided here:
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../../utils/")))
Upvotes: 2
Reputation: 14961
You don't need to worry about the path if you set your project up as a package, which in this case should be as simple as putting an empty __init__.py
into each folder:
/src
__init__.py
main.py
foo/
__init__.py
foo.py
/bar
__init__.py
bar.py
util/
__init__.py
utilities.py
Now, main.py
, foo.py
and bar.py
can import your utilities
module via a simple:
from util import utilities
Upvotes: 3