2016-09-17 32 views
1

我是新來的stackoverflow。我在編寫下面的代碼時已經從這個論壇獲得了很多幫助。下面的代碼搜索系統驅動器上的所有目錄/子目錄,但在查看'D'驅動器時,它僅查看在運行此程序的文件夾之後的那些目錄和子目錄。Python os.walk()方法

我的意思是如果我從D:\Dir1\Dir2\Dir3\myCode.py運行這個程序,它會搜索D:\Dir1\Dir2\Dir3\之後的目錄和子目錄,而不是整個'D'驅動器。它可以在同一位置運行時與其他驅動器配合使用。這是我的代碼:

import os, string 
total=0 
for driveLetter in string.ascii_uppercase: 
    try: 
     if os.path.exists(driveLetter+':'): 
      for root, dirs, docs in os.walk(top=driveLetter+':', topdown=True):    
       for name in docs: 
        try: 
         if (name.endswith(".docx")) or (name.endswith(".doc")): 
          print(os.path.join(root, name)) 
          total+=1       
        except: 
         continue 
    except: 
     continue 
print ('You have a total of ' + str(total) + ' word documents in your System') 
+0

如果後面添加什麼'\「d:」讓你獲得D:\「我有一個理論,如果沒有,它的引用d驅動器,它的計劃是其中的CWD從...發射。不是一個窗戶的人,所以我可以完全離開基地(我的斜線可能是錯的)。 – nephlm

回答

2

在Windows each process may set a current working directory on each drive separatelyD:表示驅動器D上的當前工作目錄。此處會發生此行爲,因爲在所有其他驅動器上當前工作目錄設置爲根目錄,但在D:上是D:\Dir1\Dir2\Dir3\,因爲工作目錄已更改爲劇本。要明確地參考根目錄目錄D:,您需要使用D:\。因此

drive_root = drive_letter + ':\\' # double \\ because this is a Python string literal 
if os.path.exists(drive_root): 
    for root, dirs, docs in os.walk(drive_root, topdown=True):    
+0

感謝反哈普拉,它的工作。感激。 – Timi