2013-10-26 71 views
0

我試圖執行我在Windows環境下編寫的程序, 我始終在應該從應用程序中導入文件的行上發生錯誤子文件夾中。無法獲取Python中的當前目錄路徑(Linux)

程序提供了以下錯誤,

Traceback (most recent call last): 
    File "BlackBox.py", line 26, in <module> 
    from BB_Files import BB_Expand 
ImportError: No module named BB_Files 

儘管該文件的存在BB_Expand BB_Files文件夾內,我仍然得到錯誤。

我也曾嘗試附加在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 <module> 
    from bbfiles import bbexpand 
ImportError: No module named bbfiles 

我想知道爲什麼路徑在Windows中打印效果不佳時不會打印。 我所得到的只是一個黑色空間,而不是當前目錄的路徑。

+0

嘗試向兩個文件夾添加一個'__init __。py'文件 – immortal

+0

您的意思是一個空文件? –

+0

是的,這個文件告訴python該文件夾是一個模塊,只是它的存在。 – immortal

回答

1

顯然,下面一行將拋出一個ImportError錯誤

from BB_Files import BB_Expand 
## if you comment this the next immediate line will give you same error 

因爲這是你第一次從包裝

所以導入模塊的嘗試,當你說

from <something> import <something-else> 

手段那麼,您正在從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__)) 
+0

您只需使用'print()'表示法,因爲您使用的是python3 + –

0

嘗試在兩個目錄中添加__init__.py文件。它不必包含任何內容,但必須存在。 當Python嘗試加載模塊目錄時,它首先嚐試加載此文件,因爲它可以包含有關模塊加載的額外說明(例如從正確的文件導入與平臺相關的代碼的能力)。如果Python沒有找到該文件,它可能不會將該目錄視爲Python模塊,並且無法從中導入文件。

documentation瞭解更多關於它的信息。

0

/home/pe/Desktop/AES/BB_Files目錄中添加一個名爲__init__.py的空文件應該可以解決問題。閱讀更多關於Python Docs

相關問題