1

I am using Python 3.4

I have a directory structure that looks this:

A
   B
      c.py
      d.py
      __init__.py
   C
      e.py
      f.py
      __init__.py
   g.py
   __init__.py

From g.py I can import things from both B and C modules.

I need, in e.py, to import something from c.py

I tried:

import B

and

from B.c import stuff_I_need

For both I get the error:

"No module named B".

I also tried something like:

from A.B.c import stuff_I_need

I am further confused by the fact with an identical directory structure, I can make the imports I need with Python 2.7.

Can you help me figure out what's going on?

Solution:

PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

Taken from here.

Community
  • 1
  • 1
RandomGuyqwert
  • 425
  • 6
  • 18

2 Answers2

0

When importing it looks at the the python folder for imports and the files in the local directory. If you want to import a file that is in neither of those, then I suggest using the sys module

import sys
sys.path.append(r'file-path\A') # Folder A
import B.c

If you don't want to set the full file path then you can also just backtrack to the previous directory with this for the same effect.

sys.path.append('..') # Previous Directory
Steven Summers
  • 5,079
  • 2
  • 20
  • 31
  • Alternatively, the package can be installed to site-packages depending on the purposes of `A`. But @Steven-Summers is right, it has to be on your python path. – Mike Shultz Dec 14 '15 at 17:21
  • Thank you for the answer. I did something similar: PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) – RandomGuyqwert Dec 14 '15 at 18:24
0

You need to do either

from .B import c

or

import A.B.c

Reference:

dsh
  • 12,037
  • 3
  • 33
  • 51