fir3net
PPS-Firenetbanner-780.5x190-30-03-17

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 *

 

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001