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

问题描述

我在/project上有一个名为tester.py的文件.

I have a file called tester.py, located on /project.

/project有一个名为lib的子目录,带有一个名为BoxTime.py的文件:

/project has a subdirectory called lib, with a file called BoxTime.py:

/project/tester.py
/project/lib/BoxTime.py

我想从tester导入BoxTime.我已经尝试过了:

I want to import BoxTime from tester. I have tried this:

import lib.BoxTime

结果是

Traceback (most recent call last):
  File "./tester.py", line 3, in <module>
    import lib.BoxTime
ImportError: No module named lib.BoxTime

有什么想法如何从子目录导入BoxTime?

Any ideas how to import BoxTime from the subdirectory?

编辑

__init__.py是问题所在,但不要忘记将BoxTime称为lib.BoxTime,或使用:

The __init__.py was the problem, but don't forget to refer to BoxTime as lib.BoxTime, or use:

import lib.BoxTime as BT
...
BT.bt_function()

推荐答案

在此处查看包"文档(第6.4节): http://docs.python.org/tutorial/modules.html

Take a look at the Packages documentation (Section 6.4) here: http://docs.python.org/tutorial/modules.html

简而言之,您需要放置一个名为

In short, you need to put a blank file named

__init__.py

在"lib"目录中.

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

06-08 13:31