如何从另一个目录导入.py文件? [英] How to import .py file from another directory?

查看:249
本文介绍了如何从另一个目录导入.py文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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,但是我尝试给出的错误是没有这样的模块.

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

我尝试了这个: from model import py_file

然后: import py_file

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

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?

推荐答案

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

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.

这篇关于如何从另一个目录导入.py文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆