Python方法walk()通过自上而下或自底向上遍历树来生成目录树中的文件名。
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
top - 每个以目录为根的目录,产生3元组,即(dirpath,dirname,filename)
topdown - 如果可选参数TOTODOWN为True或未指定,则从上到下扫描目录。如果topdown设置为false,则自下而上扫描目录。
onerror - 这可能会显示错误以继续遍历,或引发异常以中止遍历。
FollowLinks - 如果设置为TRUE,则访问符号链接所指向的目录。
以下示例显示walk()方法的用法。
# !/usr/bin/python import os 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))
让无涯教程编译并运行上述程序,这将自下而上地扫描所有目录和子目录
./tmp/test.py ./.bash_logout ./amrood.tar.gz ./.emacs ./httpd.conf ./www.tar.gz ./mysql.tar.gz ./test.py ./.bashrc ./.bash_history ./.bash_profile ./tmp
如果将TOPTDOWN的值更改为True,则会给出以下输出-
./.bash_logout ./amrood.tar.gz ./.emacs ./httpd.conf ./www.tar.gz ./mysql.tar.gz ./test.py ./.bashrc ./.bash_history ./.bash_profile ./tmp ./tmp/test.py
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)