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文件目录的方法