Python3 os.walk()方法

walk()方法通過遍曆樹,無論是自上而下還是自下而上生成的目錄樹中的檔案名。

語法

以下是 walk()方法的語法:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

參數

  • top --在目錄每個目錄根,得到3元組,即(dirpath, dirnames, filenames)

  • topdown -- 如果可選參數 topdown 的值是Ture或未指定,則目錄從自上而下的掃描。 如果 topdown 設置為False,目錄從自下而上的掃描。

  • onerror -- 這可能會顯示錯誤繼續遍曆檔,或引發異常中止遍曆。

  • followlinks -- 這可訪問目錄指向符號鏈接,如果設置為true。

返回值

此方法不返回任何值。

示例

下麵的示例顯示 walk()方法的使用。
# !/usr/bin/python3

import os
os.chdir("d:\\tmp")
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))

讓我們編譯並運行上述程式,這將掃描所有的目錄和子目錄,結果如下所示:
.\python2\testdir\Readme_files\Lpt_Port_Config.gif
.\python2\testdir\Readme_files\ParallelPortViever.gif
.\python2\testdir\Readme_files\softcollection.css
.\python2\testdir\Readme_files\Thumbs.db
.\python2\testdir\Readme_files\Yellov_Ball.gif
.\python2\testdir\Readme.html
.\python2\testdir\Readme_files
.\python2\testdir
.\Applicationdocs.docx
.\book.zip
.\foo.txt
.\java.ppt
.\python2
如果你將 topdown 改變前的值為 True,那麼它會得到以下結果:
.\Applicationdocs.docx
.\book.zip
.\foo.txt
.\java.ppt
.\python2
.\python2\testdir
.\python2\testdir\Readme.html
.\python2\testdir\Readme_files
.\python2\testdir\Readme_files\Lpt_Port_Config.gif
.\python2\testdir\Readme_files\ParallelPortViever.gif
.\python2\testdir\Readme_files\softcollection.css
.\python2\testdir\Readme_files\Thumbs.db
.\python2\testdir\Readme_files\Yellov_Ball.gif

上一篇: Python3檔方法 下一篇: Python3 os檔目錄的方法