accessing modules from subdirectories [solved]

Hi.

I am sorry to ask beginner questions, but there should be a simple solution. :frowning:

I try to import all functions from a module called “testmod” in a subdirectory called “test” directly beneath the calling script:

from test.testmod import *

Errormessage:

from test.testmod import *
ImportError: No module named testmod

Do I need to add the dir I want to use to the modules search path?

Is there a more simple way than:

import sys
sys.path.insert(0,'test')
import testmod
del sys.path[0]

? - Me wonders. :slight_smile:

Regards, Bigfoot29

If you were a beginner I would say that you forgot about the init.py file, or that you have a typo.

enn0x

Hi. Thx for the answer. currently there is no init…

here is the code:

test.py:

import test.testmod

testmod.testfktn()

testmod.py inside of “test”-dir:

def testfktn():
        print "works"
  • which doesn’t work.

When using:

import sys
sys.path.insert(0,'test')
import testmod
del sys.path[0]

testmod.testfktn()

instead in test.py, it works.

Is there no better and more simple way to import a module from a subdir? scratches itchie

Regards, Bigfoot29

The correct way to create a package is by creating init.py in /test.

Sorry, I should have been more explicit.
This is what your directory structure should look like:

yourscript.py
test
    test/__init__.py
    test/testmod.py

The init.py can be an empty text file.

enn0x

Ah, yep, that works. :slight_smile:

placed the empty init.py inside the test directory and could then use

import test.testmod :slight_smile:

Thanks for your help!

Regards, Bigfoot29