Have a file test.py
, located on a Directory for eg /pyproject
. and in /pyproject
have a subdirectory called api
which have two subdirectorys called gmail
and facebook
and in both directory have .py
file such as :
/pyproject/api/gmail/abc.py
/pyproject/api/facebook/xyz.py
Have import abc and xyz py file from test.py:
import api.gmail.abc
Which resulted:
File "./test.py", line 3, in <module>
import api.gmail.abc
ImportError: No module named api.gmail.abc
is There any ideas how to import xyz/abc from subdirectory to main test.py
file?
2
Answers
After Doing some R&D, Have done it Just need to create
__init__.py
(a empty py file) and add it to all subdirectory such asAnd add in main py file
You need to have an empty
__init__.py
file in each directory, it’s a marker that tells python this folder is a module. I think it should solve the problem for python2.In python3 imports have been slightly changed, and there you’ll also need to use
-m
command line parameter.If the file you’re trying to run is for example
.../pyproject/src/scraper.py
You need to set your working directory to the project root
.../pyproject/
, and run:python -m src.scraper
In this example I used a longer path to show that sub-directories are delimited by a
.
instead of/
. In your casepython -m test
should work fine.