如何从另一个目录导入.py文件? [复制]

问题描述 投票:30回答:2

此问题已经在这里有了答案:

我具有这种文件结构(目录和后箭头文件):

model -> py_file.py 
report -> other_py_file.py

主要__init__.py

import model
import report

模型目录:

import py_file

报告目录:

import other_py_file

现在在other_py_file中,我想导入py_file,但是我尝试给出的错误是没有这样的模块。

我尝试过:from model import py_file

然后:import py_file

看起来这两个文件夹彼此看不到。从其他目录导入文件的方式是什么?我是否需要在init。py文件中指定一些其他导入?

python openerp python-import
2个回答
52
投票

您可以在运行时添加到系统路径:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

到目前为止,这是最简单的方法。


19
投票

Python3:

import importlib.machinery

loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')

handle.mainFunction(parameter)

此方法可用于在文件夹结构中以您想要的任何方式导入(向后,向前无关紧要,我只是使用绝对路径来确定)。

还有在Python3中导入python模块的更普通的方法,

import importlib
module = importlib.load_module('folder.filename')
module.function()

对于为Python2提供类似的答案表示敬意Sebastian

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
© www.soinside.com 2019 - 2024. All rights reserved.