需求:掃描 Windows C 磁碟所有資料夾,找出副檔名為 .dll 的檔案並記錄完整路徑。Python 標準庫 os.walk 配合 fnmatch 可輕鬆實現,無需複雜介面實作。
import os
import fnmatch
def main():
with open('dll_list.txt', 'w', encoding='utf-8') as f:
for root, dirs, files in os.walk('C:\\'):
for name in files:
if fnmatch.fnmatch(name.lower(), '*.dll'):
full_path = os.path.join(root, name)
f.write(full_path + '\n')
print('done...')
if __name__ == '__main__':
main()
os.walk('C:\\'):遞迴遍歷目錄樹,回傳 (root, dirs, files) 三元組。fnmatch.fnmatch(name, pattern):支援萬用字元 *, ? 的模式比對,大小寫不敏感建議自行 .lower()。with open(...) as f 確保檔案正確關閉。os.path.join 跨平台相容。PermissionError。try-except 捕捉存取錯誤並記錄日誌。同樣模式可用於:
此技巧是 Python 自動化維運腳本的基礎技能。