Chinaunix首页 | 论坛 | 博客
  • 博客访问: 309016
  • 博文数量: 214
  • 博客积分: 4258
  • 博客等级: 上校
  • 技术积分: 2021
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-02 09:16
个人简介

http://blog.csdn.net/ly21st http://ly21st.blog.chinaunix.net

文章分类

全部博文(214)

文章存档

2018年(16)

2015年(1)

2014年(2)

2012年(22)

2011年(173)

分类: Python/Ruby

2011-10-10 11:09:12

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'])
 
阅读(296) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~