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?
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?
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')
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
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
Game folder is in your PYTHONPATH you can now do from Game.a import 1 in 2.py or vice versa in 1.pyfrom ..a import 1 which is relative import