當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python 3 os.walk()用法及代碼示例


描述

方法walk()通過自頂向下或自底向上遍曆樹,在目錄樹中生成文件名。

用法

以下是語法walk()方法 -

os.walk(top[, topdown = True[, onerror = None[, followlinks = False]]])

參數

  • top− 每個以目錄為根的目錄,產生 3 元組,即 (dirpath, dirnames, filenames)

  • topdown− 如果可選參數 topdown 為 True 或未指定,則自上而下掃描目錄。如果 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))

結果

讓我們編譯並運行上麵的程序,這將掃描所有目錄和子目錄 bottom-to-up

.\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.htm
.\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.htm
.\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

相關用法


注:本文由純淨天空篩選整理自 Python 3 - os.walk() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。