2013-02-05 191 views
1

基本上我有一個用Python 2.6編寫的FileExplorer類。它可以很好地工作,我可以瀏覽驅動器,文件夾等。 但是,當我到達一個特定文件夾'C:\ Documents and Settings/。*'*,os.listdir時,拋出此錯誤:Python os.listDir拋出「WindowsError:[Error 5] Access is denied:」on some folders

WindowsError:[錯誤5]訪問被拒絕:'C:\ Documents and Settings/'

這是爲什麼?是因爲這個文件夾是隻讀嗎?還是Windows正在保護和我的腳本無法訪問?!

這裏是有問題的代碼(3號線):

def listChildDirs(self): 
    list = [] 
    for item in os.listdir(self.path): 
     if item!=None and\ 
      os.path.isdir(os.path.join(self.path, item)): 
      print item 
      list.append(item) 
     #endif 
    #endfor 
    return list 
+0

哪個版本的Windows?在Vista和更高版本中,C:\ Documents and Settings是一個連接點,而不是一個真實的目錄。 – Rod

+0

這是Windows 7,抱歉忘了提。 – Radu

回答

2

在Vista和更高版本中,C:\ Documents and Settings是一個連接點,而不是一個真實的目錄。

你甚至不能直接在其中做dir

C:\Windows\System32>dir "c:\Documents and Settings" 
Volume in drive C is OS 
Volume Serial Number is 762E-5F95 

Directory of c:\Documents and Settings 

File Not Found 

可悲的是,使用os.path.isdir(),它將返回True

>>> import os 
>>> os.path.isdir(r'C:\Documents and Settings') 
True 

你可以看看這些答案來處理在Windows符號鏈接。

+0

正是我在想什麼。這對異常處理很有用。 – Mike

+0

非常感謝,這解釋了很多。 @Mike,是的,我正在考慮如何解決它 - 趕上例外。 – Radu

0

這可能是一個權限設置目錄的訪問,甚至該目錄不在那裏。您可以運行腳本以管理員身份(即獲得的一切),或嘗試這樣的事:

def listChildDirs(self): 
    list = [] 
    if not os.path.isdir(self.path): 
     print "%s is not a real directory!" % self.path 
     return list 
    try: 
     for item in os.listdir(self.path): 
      if item!=None and\ 
       os.path.isdir(os.path.join(self.path, item)): 
       print item 
       list.append(item) 
      #endif 
     #endfor 
    except WindowsError: 
     print "Oops - we're not allowed to list %s" % self.path 
    return list 

順便問一下,你有沒有聽說過?它看起來可能是你想要實現的捷徑。

+0

os.walk不會遞歸地列出所有的目錄的子項,孫子項,grand-grand子項等嗎?我想只展示給孩子們。 – Radu

+0

你可以通過返回for for循環來停止步行 – Rod

相關問題