how to import module from other directory in pytho

2020-08-03 04:04发布

问题:

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:

try using imp:

import imp
foo = imp.load_source('filename', 'File\Directory\filename.py')

this is just like importing normally now you can use the file use imported

you then use what you named it (in this case foo) like this:

foo.method()

hope thats what youre looking for!

you can also try this:

import sys
sys.path.append('folder_name')


回答2:

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


回答3:

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