Greg Brown
Greg Brown

Reputation: 1299

python unable to import module

I have my program set up using packages as followed:

-base
    -init.py
    -base_class.py
-test
    -init.py
    -test.py

When I do the import statement from base.base_class import BaseClass in the test.py I get this error when running it:

from base.base_class import BaseClass
ImportError: No module named base.base_class

How can I import this module?

Upvotes: 7

Views: 16962

Answers (4)

Serial
Serial

Reputation: 8043

there are 3 things you can do:

add an init.py file to each folder

add sys.path.append("Folder") to the top

or use imp and do;

import imp
foo = imp.load_source('filename', 'File\Directory\filename.py')

then foo will be the name of the module for example foo.method()

Upvotes: 1

guisantogui
guisantogui

Reputation: 4136

You have to create a file called "__init__.py" at python directories, then "the Python" will understand that directory as a Python package.

Upvotes: 1

amdorra
amdorra

Reputation: 1554

you nee to have an __init__.py file in each folder you import from

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 114098

at the top of test.py add

import sys
sys.path.append("..")

base is not a folder on the path...once you change this it should work

or put test.py in the same folder as base. or move base to somewhere that is on your path

Upvotes: 7

Related Questions