如何从python中的其他目录导入模块?

问题描述:

这是我的目录树

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

在 2.py 中,我想从 1.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?

尝试使用 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

然后你使用你给它命名的东西(在这个例子中是 foo),就像这样:

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

foo.method()

希望这就是您要找的!

你也可以试试这个:

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