用法:
os.walk(top, topdown=True, onerror=None, followlinks=False)通过自上而下或自下而上遍历树,在目录树中生成文件名。对于以目录
top为根的树中的每个目录(包括top本身),它会产生一个三元组(dirpath, dirnames, filenames)。dirpath是一个字符串,是目录的路径。dirnames是dirpath中子目录的名称列表(不包括'.'和'..')。filenames是dirpath中非目录文件的名称列表。请注意,列表中的名称不包含路径组件。要获取dirpath中文件或目录的完整路径(以top开头),请执行os.path.join(dirpath, name)。列表是否排序取决于文件系统。如果在生成列表期间从dirpath目录中删除或添加文件,则未指定是否包含该文件的名称。如果可选参数
topdown是True或未指定,则在其任何子目录的三元组之前生成目录的三元组(目录是自上而下生成的)。如果topdown是False,则在其所有子目录的三元组之后生成目录的三元组(目录自下而上生成)。无论topdown的值如何,都会在生成目录及其子目录的元组之前检索子目录列表。当
topdown为True时,调用者可以就地修改dirnames列表(可能使用del或切片赋值),并且walk()只会递归到名称保留在dirnames中的子目录;这可用于修剪搜索,强制执行特定的访问顺序,甚至在调用者再次恢复walk()之前通知walk()有关调用者创建或重命名的目录。当topdown为False时修改dirnames对walk 的行为没有影响,因为在自底向上模式下,dirnames中的目录是在dirpath本身生成之前生成的。默认情况下,来自
scandir()调用的错误将被忽略。如果指定了可选参数onerror,它应该是一个函数;它将使用一个参数调用,即OSError实例。它可以报告错误以继续遍历,或引发异常以中止遍历。请注意,文件名可用作异常对象的filename属性。默认情况下,
walk()不会进入解析为目录的符号链接。将followlinks设置为True以访问支持符号链接的系统上的目录。注意
请注意,如果链接指向其自身的父目录,则将
followlinks设置为True可能会导致无限递归。walk()不跟踪它已经访问过的目录。这个例子显示了起始目录下每个目录中非目录文件占用的字节数,除了它不在任何 CVS 子目录下查找:
import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print(root, "consumes", end=" ") print(sum(getsize(join(root, name)) for name in files), end=" ") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories在下一个示例中(
shutil.rmtree()的简单实现),自下而上遍历树是必不可少的,rmdir()不允许在目录为空之前删除目录:# Delete everything reachable from the directory named in "top", # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name))使用参数
top、topdown、onerror、followlinks引发审计事件os.walk。在 3.5 版中更改:这个函数现在调用os.scandir代替
os.listdir(),通过减少对os.stat.在 3.6 版中更改:接受一个path-like 对象.
相关用法
- Python os.walk()用法及代码示例
- Python os.wait()用法及代码示例
- Python os.waitid()用法及代码示例
- Python os.writev()用法及代码示例
- Python os.write()用法及代码示例
- Python os.path.normcase()用法及代码示例
- Python os.read()用法及代码示例
- Python os.DirEntry.inode()用法及代码示例
- Python os.closerange()用法及代码示例
- Python os.set_blocking()用法及代码示例
- Python os.pathconf()用法及代码示例
- Python os.chflags()用法及代码示例
- Python os.WCOREDUMP()用法及代码示例
- Python os.fork()用法及代码示例
- Python os.ctermid()用法及代码示例
- Python os.mkfifo()用法及代码示例
- Python os.tcsetpgrp()用法及代码示例
- Python os.path.commonpath()用法及代码示例
- Python os.path.splitdrive用法及代码示例
- Python os.mkdir()用法及代码示例
注:本文由纯净天空筛选整理自python.org大神的英文原创作品 os.walk。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
