Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a module from outside your file folder in Python? [duplicate]

Tags:

python

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?

like image 423
Sean Francis N. Ballais Avatar asked Jul 21 '14 15:07

Sean Francis N. Ballais


People also ask

How do you call a module from another directory in Python?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

How do I import a module from the outside directory?

Method 1: Using sys. The sys. path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.

What does __ init __ py do in Python?

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.

Does module need to be in same directory?

Answer. No, files can be imported from different directories.


1 Answers

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 * 
like image 97
aruisdante Avatar answered Oct 05 '22 23:10

aruisdante