python之import子目錄文件


問題:

 

 

在pre_tab.py文件下:

 

print("AA")
from test.te import login1
login1()

 

 

from test.te import login1
程序中此句引入當前目錄下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 <module>
    from test.te import login1
ImportError: No module named 'test.te'

 

查找原因是test目錄下沒有創建__init__.py文件(其實默認是有創建的,但我原先刪了)
 
 

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將目錄視為包含包; 這樣做是為了防止具有公用名稱的目錄(例如字符串)意外隱藏模塊搜索路徑上稍后出現的有效模塊。 在最簡單的情況下,__init__.py可以只是一個空文件,但它也可以執行包的初始化代碼或設置__all__變量,稍后描述。
 
 

解決方法:

在test目錄下建__init__().py文件
 
 
補充別人的看法;
  如官網所述,此文件使得這個目錄被包含到當前的python package中,
  我理解就是成為一個module,import查找當前目錄時這個目錄能被識別了,然后import成功.
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM