用法:
os.walk(top, topdown=True, onerror=None, followlinks=False)通過自上而下或自下而上遍曆樹,在目錄樹中生成文件名。對於以目錄
top為根的樹中的每個目錄(包括top本身),它會產生一個三元組(dirpath, dirnames, filenames)。dirpath是一個字符串,是目錄的路徑。dirnames是dirpath中子目錄的名稱列表(不包括'.'和'..')。filenames是dirpath中非目錄文件的名稱列表。請注意,列表中的名稱不包含路徑組件。要獲取dirpath中文件或目錄的完整路徑(以top開頭),請執行os.path.join(dirpath, name)。列表是否排序取決於文件係統。如果在生成列表期間從dirpath目錄中刪除或添加文件,則未指定是否包含該文件的名稱。如果可選參數
topdown是True或未指定,則在其任何子目錄的三元組之前生成目錄的三元組(目錄是自上而下生成的)。如果topdown是False,則在其所有子目錄的三元組之後生成目錄的三元組(目錄自下而上生成)。無論topdown的值如何,都會在生成目錄及其子目錄的元組之前檢索子目錄列表。當
topdown為True時,調用者可以就地修改dirnames列表(可能使用del或切片賦值),並且walk()隻會遞歸到名稱保留在dirnames中的子目錄;這可用於修剪搜索,強製執行特定的訪問順序,甚至在調用者再次恢複walk()之前通知walk()有關調用者創建或重命名的目錄。當topdown為False時修改dirnames對walk 的行為沒有影響,因為在自底向上模式下,dirnames中的目錄是在dirpath本身生成之前生成的。默認情況下,來自
scandir()調用的錯誤將被忽略。如果指定了可選參數onerror,它應該是一個函數;它將使用一個參數調用,即OSError實例。它可以報告錯誤以繼續遍曆,或引發異常以中止遍曆。請注意,文件名可用作異常對象的filename屬性。默認情況下,
walk()不會進入解析為目錄的符號鏈接。將followlinks設置為True以訪問支持符號鏈接的係統上的目錄。注意
請注意,如果鏈接指向其自身的父目錄,則將
followlinks設置為True可能會導致無限遞歸。walk()不跟蹤它已經訪問過的目錄。這個例子顯示了起始目錄下每個目錄中非目錄文件占用的字節數,除了它不在任何 CVS 子目錄下查找:
import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print(root, "consumes", end=" ") print(sum(getsize(join(root, name)) for name in files), end=" ") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories在下一個示例中(
shutil.rmtree()的簡單實現),自下而上遍曆樹是必不可少的,rmdir()不允許在目錄為空之前刪除目錄:# Delete everything reachable from the directory named in "top", # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name))使用參數
top、topdown、onerror、followlinks引發審計事件os.walk。在 3.5 版中更改:這個函數現在調用os.scandir代替
os.listdir(),通過減少對os.stat.在 3.6 版中更改:接受一個path-like 對象.
相關用法
- Python os.walk()用法及代碼示例
- Python os.wait()用法及代碼示例
- Python os.waitid()用法及代碼示例
- Python os.writev()用法及代碼示例
- Python os.write()用法及代碼示例
- Python os.path.normcase()用法及代碼示例
- Python os.read()用法及代碼示例
- Python os.DirEntry.inode()用法及代碼示例
- Python os.closerange()用法及代碼示例
- Python os.set_blocking()用法及代碼示例
- Python os.pathconf()用法及代碼示例
- Python os.chflags()用法及代碼示例
- Python os.WCOREDUMP()用法及代碼示例
- Python os.fork()用法及代碼示例
- Python os.ctermid()用法及代碼示例
- Python os.mkfifo()用法及代碼示例
- Python os.tcsetpgrp()用法及代碼示例
- Python os.path.commonpath()用法及代碼示例
- Python os.path.splitdrive用法及代碼示例
- Python os.mkdir()用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 os.walk。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
