Python遞迴處理目錄下的檔案
阿新 • • 發佈:2019-01-13
本文首發於我的個人部落格:Suixin’s Blog
原文: https://suixinblog.cn/2019/01/os-walk.html 作者: Suixin
使用os
模組的os.walk()
函式可以遞迴地遍歷目錄。
用法
os.walk(top, topdown=True, None, followlinks=False)
top:要遍歷的目錄地址;
topdown:遍歷優先順序。True為先遍歷top目錄,False為先遍歷top子目錄。
例子
目錄結構為:
import os
for root, dirs, files in os.walk( "Suixin/"):
print(root)
print(dirs)
print(files, "\n\n")
可看到,函式先遍歷了主目錄Suixin/
,其下有兩個子目錄other
和Blog
、兩個檔案.DS_Store
和code1.py
;再分別遍歷了兩個子目錄other
和Blog
,其下無子子目錄,只有檔案。
該方法對於遞迴處理目錄檔案非常有效,而且函式執行很快,消耗極小的時間。