user2984887
user2984887

Reputation:

Python : Having issue to Import a function from a file in a different folder

in my python project, I have 2 folders:

folder_A
    __init__.py
    a.py
    b.py
    c.py

folder_B
    __init__.py
    main.py

With in main.py, I am using this command:

from folder_A.a import function1

When running the program I get:

ImportError: No module named 'folder_A'

What am I doing wrong?

Upvotes: 1

Views: 107

Answers (1)

Peter Gibson
Peter Gibson

Reputation: 19574

Upon execution, the current folder is added to the python path. However if you are executing

~/myproject/$ python folder_B/main.py

Then the current path resolves inside folder_B, so folder_A is not in the python path.

You can execute the main module from the upper project folder:

~/myproject/$ python -m folder_B.main

Otherwise, you can set the PYTHONPATH env var

~/myproject/folder_B/$ PYTHONPATH=".." python main.py

Upvotes: 3

Related Questions