How do I import a python module from another folder ?

Within this article we will show you how to import a python module that is located within a different folder.

This example will be based upon your folder structure including a folder named ‘module’ and the path ‘/opt/django/myproject/’ already being within your python system path.

Example Folder Structure

Below shows you a quick example of the layout and the location of the module that we will later import.

/opt/django/myproject
.
|– __init__.py
|– modules
| |– __init__.py
| |– validate.py

Check Path

Next check your python system paths. 

Python 2.4.3 (#1, Jan 9 2013, 06:47:03)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
(InteractiveConsole)
>>> import sys
>>> print sys.path
[‘/opt/django/myproject‘, …… (remaining output omitted)

Add __init__

Ensure that a file called __init__ is added to the folder that contains the module you want to import. This file is typically empty.

Import Module

Finally import the module using the following syntax ‘from <folder>.<filename> import <module>’. So based on our example this will look like,

Python 2.4.3 (#1, Jan 9 2013, 06:47:03)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
(InteractiveConsole)
>>> from modules.validate import *

 

Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial