skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 as

     /pyproject/
        api/
          __init__.py
          gmail/
              __init__.py
              abc.py
    
          facebook/
             __init__.py
             xyz.py
    

    And add in main py file

    from api.gmail.abc import *
    or
    import api.gmail.abc
    

  2. 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 case python -m test should work fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search