Python3-os-walk

提供:Dev Guides
移動先:案内検索

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))

結果

上記のプログラムをコンパイルして実行します。これにより、すべてのディレクトリとサブディレクトリが下から上にスキャンされます。

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