0

I've seen tips on how to import from a subfolder. The problem is importing from another folder in the same parent folder. The current structure is like this:

test 
__init__.py
|-- folder1
|-- __init__.py
| |-- A.py
|-- folder2
| |-- __init__.py
| |-- B.py

A.py is:

hi = 1 
print "hi", hi

B.py is:

from folder1 import A

print "imported"

When I do python B.py, I get an error:

  File "B.py", line 1, in <module>
    from folder1 import A
ImportError: No module named folder1

How can I import A.py? Ideally, folder structure does not change.

5
  • What python version? Commented Nov 19, 2015 at 21:40
  • what is the python path? Commented Nov 19, 2015 at 21:41
  • python version 2.7, I'm using anaconda python in my home directory, /Applications/anaconda/bin/python Commented Nov 19, 2015 at 21:42
  • 1
    Does this help? stackoverflow.com/questions/14132789/… Commented Nov 19, 2015 at 21:47
  • This may help: stackoverflow.com/questions/33773202/… Commented Nov 19, 2015 at 23:26

1 Answer 1

1

The problem here is that folder1 and folder2 are subpackages, and the package is the parent directory i.e. test.

Whatever path the parent directory of test is will need to be in your sys.path. You can do this, for example, with the PYTHONPATH environment variable.

Then you should have, in module B.py:

from test.folder1 import A
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.