python import 文件路径_python之import子目录文件
問題:
在pre_tab.py文件下:
print("AA")
from test.te import login1
login1()
from test.te import login1
程序中此句引入當(dāng)前目錄下test目錄中的te.py文件中的login1對象(方法)
但是一直報錯 importError 沒找到test.te這個模塊
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/laonanhai/shop_store/pre_tab.py", line 21, in
from test.te import login1
ImportError: No module named 'test.te'
查找原因是test目錄下沒有創(chuàng)建__init__.py文件(其實默認(rèn)是有創(chuàng)建的,但我原先刪了)
The?__init__.py?files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as?string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case,?__init__.py?can just be an empty file, but it can also execute initialization code for the package or set the?__all__?variable, described later.
渣渣谷哥翻譯:
需要__init__.py文件來使Python將目錄視為包含包; 這樣做是為了防止具有公用名稱的目錄(例如字符串)意外隱藏模塊搜索路徑上稍后出現(xiàn)的有效模塊。 在最簡單的情況下,__init__.py可以只是一個空文件,但它也可以執(zhí)行包的初始化代碼或設(shè)置__all__變量,稍后描述。
解決方法:
在test目錄下建__init__().py文件
補充別人的看法;
如官網(wǎng)所述,此文件使得這個目錄被包含到當(dāng)前的python package中,
我理解就是成為一個module,import查找當(dāng)前目錄時這個目錄能被識別了,然后import成功.
總結(jié)
以上是生活随笔為你收集整理的python import 文件路径_python之import子目录文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中输入的字怎么表示_简单讲解
- 下一篇: python 中cookie_使用Pyt