0

Possible Duplicate:
How to do relative imports in Python?

So I'm trying to include a module that's a folder up from my python file and then multiple folders in.

So the folder hierarchy goes as:

\Folder\
    \Folder\First\
        \Folder\First\myPythonFile.py
    \Folder\Second\
        \Folder\Second\AnotherFolder\
            \Folder\Second\AnotherFolder\addedFile.py

I want to include the addedFile.py into my myPythonFile.py. I'm not sure how this is accomplished.

Community
  • 1
  • 1
jamby
  • 606
  • 8
  • 17
  • 1
    Is `Second` a python package? Is it something that should be added to a virtualenv or your PYTHONPATH so it's accessible from everywhere? – Wooble Feb 05 '13 at 16:55

1 Answers1

1

relative imports are possible in Python since 2.5 (maybe 2.4)

if you add two empty __init__.py files in Second and Second\AnotherFolder folders, according to PEP 328 you can write:

 from ..Second.AnotherFolder.addedFile import eggs

inside myPythonFile.py

to import the desired module (in my example eggs)

(adding __init__.py files inside your folders transforms them into packages)

ALTERNATIVE APPROACH

if you don't want to create packages for your Second folder you can alter your sys.path in order to include your Second\AnotherFolder folder:

import sys
import os
sys.path.append(sys.path.append(os.path.abspath('../Second/AnotherFolder')))
import addedFile

but I discurage this approach, the reasons are explained here.

Community
  • 1
  • 1
furins
  • 4,979
  • 1
  • 39
  • 57