Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import os
- class traverse_file:
- """ traverse files """
- def __init__(self, base='.', ext=['.xls', '.xlsx']):
- self.base = base # base dir
- self.ext = ext # match file exten
- self.cdir = None # curent dir
- self.citer = None # current iter
- self.name = None
- def __str__(self):
- return os.path.join(self.name[0], self.name[1])
- def __iter__(self):
- self.cdir = [os.listdir(self.base)]
- self.citer = [iter(self.cdir[-1])]
- self.name = [self.base, '']
- return self
- def __next__(self):
- try:
- while True:
- f = next(self.citer[-1])
- self.name[-1] = f;
- fn = os.path.join(self.name[0], self.name[1])
- if os.path.isfile(fn):
- if os.path.splitext(f)[-1] in self.ext:
- return self
- else:
- return next(self)
- if os.path.isdir(fn):
- if len(os.listdir(fn)) == 0:
- raise StopIteration
- self.cdir.append(os.listdir(fn))
- self.citer.append(iter(self.cdir[-1]))
- self.name[0] = fn
- return next(self)
- except StopIteration:
- if len(self.cdir) == 1:
- raise StopIteration
- self.cdir.pop()
- self.citer.pop()
- self.name[0] = os.path.split(self.name[0])[0]
- return next(self)
- if __name__ == '__main__':
- for n, f in enumerate(traverse_file(), 1):
- print('{}: {}'.format(n, f))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement