What is the Python way to walk a directory tree?

后端 未结 11 1602
走了就别回头了
走了就别回头了 2020-12-06 09:52

I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I\'m using Python 3.2

from os import *
from os.pat         


        
11条回答
  •  攒了一身酷
    2020-12-06 10:18

    Instead of the built-in os.walk and os.path.walk, I use something derived from this piece of code I found suggested elsewhere which I had originally linked to but have replaced with inlined source:

    import os
    import stat
    
    class DirectoryStatWalker:
        # a forward iterator that traverses a directory tree, and
        # returns the filename and additional file information
    
        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:
                    # pop next directory from stack
                    self.directory = self.stack.pop()
                    self.files = os.listdir(self.directory)
                    self.index = 0
                else:
                    # got a filename
                    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
    
    if __name__ == '__main__':
        for file, st in DirectoryStatWalker("/usr/include"):
            print file, st[stat.ST_SIZE]
    

    It walks the directories recursively and is quite efficient and easy to read.

提交回复
热议问题