44

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?

1

3 Answers 3

64

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 * 
Sign up to request clarification or add additional context in comments.

6 Comments

what is ".." in here, please explain
It's standard path semantics for "up one directory" when dealing with a relative path.
if you want to up 2 directory, just replace '..' to '../..'
Well, not quite. This is inside a join block. So you'd do join('..','..','config')
Instead of '..' one can use os.path.pardir . So it becomes: sys.path.append(os.path.abspath(os.path.join(os.path.pardir, 'config')))
|
20

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.

Comments

13

Add the app directory to the module search path.

For example:

PYTHONPATH=/path/to/appname python test.py 

5 Comments

you're a legend!
Can you elaborate please?
@Mohith7548, prepend PYTHONPATH=/path/to/appname before the command. (assuming unix, the module is in /path/to/appname directory)
Okay, that's informative. How about in windows?
@Mohith7548 Execute set PYTHONPATH=..., then the command.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.