Posted By

laurenceosx on 11/23/09


Tagged

python filemgmt


Versions (?)

GlobDirWalker


 / Published in: Python
 

URL: http://www.faqts.com/knowledge_base/view.phtml/aid/2682/fid/245

  1. import os
  2. import fnmatch
  3.  
  4. class GlobDirWalker:
  5. # lpt http://www.faqts.com/knowledge_base/view.phtml/aid/2682/fid/245
  6. # a forward iterator that traverses a directory tree
  7.  
  8. def __init__(self, directory, pattern="*"):
  9. self.stack = [directory]
  10. self.pattern = pattern
  11. self.files = []
  12. self.index = 0
  13.  
  14. def __getitem__(self, index):
  15. while 1:
  16. try:
  17. file = self.files[self.index]
  18. self.index = self.index + 1
  19. except IndexError:
  20. # pop next directory from stack
  21. self.directory = self.stack.pop()
  22. self.files = os.listdir(self.directory)
  23. self.index = 0
  24. else:
  25. # got a filename
  26. fullname = os.path.join(self.directory, file)
  27. if os.path.isdir(fullname) and not os.path.islink(fullname):
  28. self.stack.append(fullname)
  29. if fnmatch.fnmatch(file, self.pattern):
  30. return fullname

Report this snippet  

You need to login to post a comment.