我试图执行在Windows环境下在Windows中编写的程序,在从子文件夹导入文件的那一行上,我一直遇到错误。
该程序出现以下错误,
Traceback (most recent call last):
File "BlackBox.py", line 26, in
from BB_Files import BB_Expand
ImportError: No module named BB_Files
尽管BB_Files文件夹中存在文件BB_Expand,但仍然出现错误。
我也尝试过在Python中附加当前目录的路径,
sys.path.append("/home/pe/Desktop/AES")
# Sub-Folders of AES are also accessible
sys.path.append("/home/pe/Desktop/AES/BB_Files")
但是还是没有运气
这是文件结构,
/home/pe/Desktop/AES/Main.py
/home/pe/Desktop/AES/BB_Files
/home/pe/Desktop/AES/BB_Files/BB_Days.py
/home/pe/Desktop/AES/BB_Files/BB_Expand.py
/home/pe/Desktop/AES/BB_Files/BB_Steps.py
这是ls -l命令的输出,
drwxrwx--x 4 pe users 4096 Oct 26 21:43 BB_Files
-rw-rw---- 1 pe users 15284 Oct 26 22:04 Main.py
这是文件中的一些初始代码,
import sys # sys.argv ; sys.path, sys.exit
import os
import hashlib
import struct # Interpret strings as packed binary data
import getopt # for Runtime arguments
import time
from datetime import date
# Append Paths from where the Files would be Imported.
sys.path.append("/home/pe/Desktop/AES")
# Sub-Folders of AES are also accessible
sys.path.append("/home/pe/Desktop/AES/BB_Files")
# Sub-Fodlers of BB_Files are also accessible now (Tables)
from BB_Files import BB_Expand
from BB_Files import BB_Steps
from BB_Files import BB_Days
这是给出错误的行,
from BB_Files import BB_Expand
该程序在此行之后无法运行,因为Python找不到此模块。
但是当我尝试打印当前目录的路径时,我什么也没看到,
print("Path is:",os.path.dirname(__file__))
print("sufiyan")
输出:
('Path is:', '')
sufiyan
Traceback (most recent call last):
File "BlackBox.py", line 25, in
from bbfiles import bbexpand
ImportError: No module named bbfiles
我想知道为什么在Windows中可以正常打印时未打印路径。我得到的只是一个空格,而不是当前目录的路径。
解决方案
显然,以下行将引发ImportError错误
from BB_Files import BB_Expand
## if you comment this the next immediate line will give you same error
由于这是您首次尝试从包中导入模块
所以,当你说
from import
表示您是module/class/function从package/module
在您的情况下,它是一个package,可能是一个称为__init__.py被放置在目录中的文件,因此python会将目录视为一个包。
## try this to get your directory name
print __file__
print "Path is:", os.path.dirname(os.path.abspath(__file__))