Home > front end >  import function from another folder's file
import function from another folder's file

Time:04-16

My project directory looks like this:

project/
├─ new/
│  ├─ test.py
├─ docs.py
├─ main.py

Within my main.py, I import a function from docs.pylike this:

from docs import get_my_conn

and it works fine.

How can I import the same thing within new/test.py as well? I tried:

from ..docs import get_my_conn

but I get this error:

ImportError: attempted relative import with no known parent package

CodePudding user response:

Add an empty __init__.py to project/. This will make project be treated as a package, and you can import functions from its modules.

The revised tree should look like:

project/
├─ new/
│  ├─ test.py
├─ __init__.py
├─ docs.py
├─ main.py

CodePudding user response:

in main.py write :

from new import test

and if you want to get a function from test.py then you have to write:

from new.test import your_function

  • Related