0

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?

mridul
  • 1,986
  • 9
  • 29
  • 50

3 Answers3

6

Use imp.

import imp
foo = imp.load_source('filename', 'File\Directory\filename.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')
apaderno
  • 28,547
  • 16
  • 75
  • 90
Serial
  • 7,925
  • 13
  • 52
  • 71
1

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
denz
  • 386
  • 1
  • 6
0

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
Ewan
  • 14,592
  • 6
  • 48
  • 62