Home  >  Article  >  Backend Development  >  Python引用(import)文件夹下的py文件的方法

Python引用(import)文件夹下的py文件的方法

WBOY
WBOYOriginal
2016-06-06 11:32:411233browse

Python的import包含文件功能就跟PHP的include类似,但更确切的说应该更像是PHP中的require,因为Python里的import只要目标不存在就报错程序无法往下执行。要包含目录里的文件,PHP中只需要给对路径就OK。Python中则不同,下面来看看这个例子。

目录结构:

a.py 要 import dir目录下的 b.py 文件。a.py代码如下:

代码如下:


# coding=utf-8
"import dir 目录下的 b.py 文件"
 
import dir.b
 
print dir.b.name


执行 a.py 报错

提示找不到这个模块的名字 dir.b 。通过查找官方文档,发现要包含目录下的文件时需要在目录下声明一个__init__.py文件,即使这个文件是空的也可以。当然这个文件也可以初始一些数据。

于是在 dir 下新建 __init__.py文件,目录结构如下:

重新执行a.py,一切OK!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn