What is the correct way in Python to import a module from a directory one level up? The directory is a Python package with all of these modules, and I have an auxiliary directory with code that needs these modules.
The following works are just fine, but it's just a hack. I would recommend / pythonic.
import sys sys.path.append("../") from fruit import Fruit print("OK")
Directory structure:
pkg1 __init__.py fruit.py +sub_pkg __init__.py recipe.py
fruit.py content
class Fruit: def get_name(self): print("Fruit name")
the contents of sub_pkg/recipe.py .. only one import line:
from fruit import Fruit
When I run:
python recipe.py
he gives the following error.
Traceback (most recent call last): File "recipe.py", line 2, in <module> from fruit import Fruit ImportError: No module named fruit
I also tried: from pkg1.fruit import Fruit , does not work. Also looked at other similar questions .. python -m recipe.py or python -m sub_pkg/recipe.py does not work.
source share