42

How can I access modules from another folder?

Here's the file structure:

/<appname>
    /config
        __init__.py
        config.py
    /test
        test.py # I'm here

I wanted to access the functions from config.py from test.py . How would I do this?
Here is my import:

import config.config

When I run the test.py script, it will always say:

ImportError: No module named config.config

Did I do something wrong?

Vikrant
  • 4,920
  • 17
  • 48
  • 72
Sean Francis N. Ballais
  • 2,338
  • 2
  • 24
  • 42
  • You can use `os.path` shenanigans to move around your relative path. http://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path?rq=1 – Cory Kramer Jul 21 '14 at 15:22

3 Answers3

60

The simplest way is to modify the sys.path variable (it defines the import search path):

# Bring your packages onto the path
import sys, os
sys.path.append(os.path.abspath(os.path.join('..', 'config')))

# Now do your import
from config.config import *
aruisdante
  • 8,875
  • 2
  • 30
  • 37
18

Yo can only import modules that are visible by your environment. You can check the environment using this.

import sys
print sys.path

As you will see sys.path is a list so you can append elements to it:

sys.path.append('/path_to_app/config')

And you should be able to import your module.

BTW: There is plenty of questions about this.

Hristo Ivanov
  • 679
  • 8
  • 25
11

Add the app directory to the module search path.

For example:

PYTHONPATH=/path/to/appname python test.py
falsetru
  • 357,413
  • 63
  • 732
  • 636