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