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?

1
  • @Haidro similar but i am looking for simple method(without create distutils packages). Commented Jul 26, 2013 at 9:00

3 Answers 3

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')
Sign up to request clarification or add additional context in comments.

1 Comment

plus one for sys.path.append('folder_name')
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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.