Sandro Munda
Sandro Munda

Reputation: 41078

What's the best way to retrieve the module path from the project in python?

| foo
|   main.py
|---- one
|    | __init__.py
|------ two
|      | __init__.py

Consider the __init__.py file situated in the foo/one/two/__init__.py. In this file, I want to print the module PATH :

foo/one/two/

What the best way to do that ?

Upvotes: 1

Views: 88

Answers (2)

John Montgomery
John Montgomery

Reputation: 9058

Each module will have a __name__ attribute, which will give you the dot syntax attribute name of the module. e.g.:


from one import two
print two.__name__

This should yield:


one.two

You could then simply replace the dots with the relevant file separater:


import os.path
from one import two
print two.__name__.replace('.', os.path.sep)

This will print (on Linux/Unix etc):


one/two

Or on Windows:


one\two

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599956

from foo.one import two
print two.__file__

Upvotes: 1

Related Questions