python遍历目录的例子(不用递归)

作者:简简单单 2014-04-03
 代码如下 复制代码


import os,stat

class DirectoryStatWalker:
    def __init__(self,directory):
        self.stack=[directory]
        self.files=[]
        self.index=0

    def __getitem__(self,index):
        while 1:
            try:
                file=self.files[self.index]
                self.index=self.index+1
            except IndexError:
                self.directory = self.stack.pop()
                self.files = os.listdir(self.directory)
                self.index = 0
            else:
                fullname = os.path.join(self.directory,file)
                st = os.stat(fullname)
                mode = st[stat.ST_MODE]
                if stat.S_ISDIR(mode) and not stat.S_ISLNK(mode):
                    self.stack.append(fullname)
                return fullname,st

for file,st in  DirectoryStatWalker(r'F:btsyncmovie'):
    print(file,st[stat.ST_SIZE])

这里没用使用递归的方式来做,但是结果却是一样的。

相关文章

精彩推荐