3

For:

app/
__init__.py
abc.py
  mod/
  __init__.py
  def.py

How would I import abc.py from def.py?

EroSan
  • 339
  • 5
  • 13
  • possible duplicate of [Python Import from parent directory](http://stackoverflow.com/questions/4542352/python-import-from-parent-directory) – Wooble Mar 09 '11 at 14:58

2 Answers2

8

to import module 'abc.py' that is in the parent directory of your current module:

import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir) 
import abc
Remi
  • 20,619
  • 8
  • 57
  • 41
2

in module def if you want to import say abc just do:

from ..abc import *

Note: as def is a python keyword, using that name for a module does not sound like a good idea.

kriss
  • 23,497
  • 17
  • 97
  • 116
  • I get an invalid syntax error when doing `import ..abc` and a Attempted relative import error if I try to `from ..abc import testfunc`. – EroSan Mar 09 '11 at 15:14
  • The second syntax is the right one for relative imports I was a bit too fast to answer. I use it, but in deployed modules. I believe it does not work if you try to run python file directly from command line. – kriss Mar 09 '11 at 16:52