欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python walk_Python os.walk()方法

发布时间:2025/4/16 python 51 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python walk_Python os.walk()方法 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Python的walk()方法通过自上而下或自下而上地遍历树来生成目录树中的文件名。

语法

以下是walk()方法的语法 -

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

参数

top - 根目录下的每个目录产生3元组,即(dirpath,dirnames,filenames)

topdown - 如果可选参数上限为True或未指定,则从上到下扫描目录。 如果上限设置为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

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

总结

以上是生活随笔为你收集整理的python walk_Python os.walk()方法的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。