'can't import function from different module/file

I'm super new to this and this is my first time posting on forum.. trying to import a function from books.py to be used in logic.py

File structure:

application
├── app
│   └── __init__.py (empty)
│   └── books.py
│── app2
│    └── logic.py
|── __init__.py (empty)

i've tried:

from application.app import books

and

import sys
sys.path.insert(0, "/user/application/app")
from book import function_name

i keep getting an error that reads: ModuleNotFoundError: No module named 'app'

i've also tried putting import books into the __init__.py and then running logic.py, but still same error.

I'm new to this, but i feel like it should be a lot simpler than this.



Solution 1:[1]

Here is how it should work - call a function that exists in directory app1 from another program/module that exists in directory app2.

C:\>mkdir py_app\app1

C:\>mkdir py_app\app2

C:\>cd py_app\app1

C:\py_app\app1>cat>__init__.py

C:\py_app\app1>tree c:\py_app
Folder PATH listing for volume OS
Volume serial number is 00000029 02D0:5C8E
C:\PY_APP
????app1
????app2

C:\py_app\app1>cat>first.py
def fun():
    print('first')
 
C:\py_app\app1>cd ..\app2

C:\py_app\app2>cat>second.py
import sys
sys.path.insert(0,'c:/py_app')
from app1.first import fun
fun()

C:\py_app\app2>python second.py
first

C:\py_app\app2>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pankaj