from nt import *
def walk(top, topdown=True, onerror=None):
from os.path import join, isdir, islink
# We may not have read permission for top, in which case we can't
# get a list of the files the directory contains. os.path.walk
# always suppressed the exception then, rather than blow up for a
# minor reason when (say) a thousand readable directories are still
# left to visit. That logic is copied here.
try:
# Note that listdir and error are globals in this module due
# to earlier import-*.
names = listdir(top)
except error, err:
if onerror is not None:
onerror(err)
return
dirs, nondirs = [], []
for name in names:
if isdir(join(top, name)):
dirs.append(name)
else:
nondirs.append(name)
if topdown:
yield top, dirs, nondirs
for name in dirs:
path = join(top, name)
if not islink(path):
for x in walk(path, topdown, onerror):
yield x
if not topdown:
yield top, dirs, nondirs
******************************************
#以下为测试代码
s=walk('D:/liyuan1',False)
for n in s:
print n
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
topdown=True运行结果
('D:/liyuan1', ['liyuan2'], ['liyuan1_aa1.txt', 'liyuan1_aa2.txt'])
('D:/liyuan1\\liyuan2', ['liyuan3'], ['liyuan2_aa1.txt', 'liyuan2_aa2.txt'])
('D:/liyuan1\\liyuan2\\liyuan3', ['liyuan4'], ['liyuan3_aa1.txt', 'liyuan3_aa2.txt'])
('D:/liyuan1\\liyuan2\\liyuan3\\liyuan4', [], ['liyuan4_aa1.txt', 'liyuan4_aa2.txt'])
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
topdown=False运行结果
('D:/liyuan1\\liyuan2\\liyuan3\\liyuan4', [], ['liyuan4_aa1.txt', 'liyuan4_aa2.txt'])
('D:/liyuan1\\liyuan2\\liyuan3', ['liyuan4'], ['liyuan3_aa1.txt', 'liyuan3_aa2.txt'])
('D:/liyuan1\\liyuan2', ['liyuan3'], ['liyuan2_aa1.txt', 'liyuan2_aa2.txt'])
('D:/liyuan1', ['liyuan2'], ['liyuan1_aa1.txt', 'liyuan1_aa2.txt'])
阅读(329) | 评论(0) | 转发(0) |