how to import module from other directory in python?

Question:

This is my directory tree

Game/
   a/
      1.py
      ...
   b/
      2.py

In 2.py I want import function display from 1.py. First I keep both file in same folder there is no problem.But how to import from other location?

Asked By: mridul

||

Answers:

Use imp.

import imp
foo = imp.load_source('filename', 'FileDirectoryfilename.py')

This is just like importing normally. You can then use the file. For example, if that file contains method(), you can call it with foo.method().

You can also try this.

import sys
sys.path.append('folder_name')
Answered By: Serial

Make sure you have a __init__.py file in any directory you want to import from and then you have 2 options;

e.g. Your code will now look like this:

Game/
   __init__.py
   a/
      __init__.py
      1.py
      ...
   b/
      __init__.py
      2.py
  1. If your Game folder is in your PYTHONPATH you can now do from Game.a import 1 in 2.py or vice versa in 1.py
  2. from ..a import 1 which is relative import
Answered By: Ewan

You have two options:

Add another folder to sys.path and import it by name

import sys
sys.path.append('../a')

import mod1
# you need to add `__init__.py` to `../a` folder
# and rename `1.py` to `mod1.py` or anything starts with letter

Or create distutils package and than you will be able to make relative imports like

 from ..a import mod1
Answered By: denz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.