walk(top, topdown=True, οnerrοr=None, followlinks=False)是一个文件树结构生成器函数,返回值是一个三元素的元组:(top, dirs, nondirs),top是输入的目录名称,dirs是top下面所有子目录的名称,nondirs是top下面所有文件的名称。
使用实例:
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
例如在D:/test/下有如下目录结构:
A
---C
------1.txt
---1.txt
---2.txt
B
1.txt
2.txt
3.txt
使用如下代码遍历该目录结构:
from os import walk
for top, dirs, files in walk("D:/test"):
print(top)
print(dirs)
print(files)
遍历结果如下:
D:/test
['A', 'B']
['1.txt', '2.txt', '3.txt']
D:/test\A
['C']
['1.txt', '2.txt']
D:/test\A\C
[]
['1.txt']
D:/test\B
[]
[]