Python 如何从另一个目录导入 .py 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22955684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:02:54  来源:igfitidea点击:

How to import .py file from another directory?

pythonopenerppython-import

提问by Andrius

I have this structure of files (directory and after arrow files):

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

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

main __init__.py:

主要__init__.py

import model
import report

model directory:

模型目录:

import py_file

report directory:

报告目录:

import other_py_file

now in other_py_fileI want to import py_file, but what ever I try I give error that there is no such module.

现在other_py_file我想导入py_file,但是无论我尝试什么,我都会给出没有这样的模块的错误。

I tried this: from model import py_file

我试过这个: from model import py_file

Then: import py_file

然后: import py_file

Looks like these two folders don't see each other. What is the way to import file from other directory? Do I need to specify some additional imports in init.py files?

看起来这两个文件夹看不到对方。从其他目录导入文件的方法是什么?我需要在init.py 文件中指定一些额外的导入吗?

采纳答案by Alex Thornton

You can add to the system-path at runtime:

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

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

import py_file

This is by far the easiest way to do it.

这是迄今为止最简单的方法。

回答by Torxed

Python3:

蟒蛇3:

import importlib.machinery

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

handle.mainFunction(parameter)

This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).

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

There's also the more normal way of importing a python module in Python3,

在 Python3 中还有更正常的方式导入 python 模块,

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

Kudos to Sebastianfor spplying a similar answer for Python2:

荣誉对塞巴斯蒂安的spplying为Python2了类似的回答:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()