python目录遍历代码,python目录,如下python实现目录
python目录遍历代码,python目录,如下python实现目录
如下python实现目录遍历:
import osclass iterdir(object): def __init__(self, path, deep=False): self._root = path self._files = None self.deep = deep def __iter__(self): return self def next(self): if self._files: join = os.path.join d = self._files.pop() r = join(self._root, d) if self.deep and os.path.isdir(r): self._files += [join(d,n) for n in os.listdir(r)] elif self._files is None: self._files = os.listdir(self._root) if self._files: return self._files[-1] else: raise StopIteration# sample:# a deep traversal of directories which starts with a vowel#it = iterdir('.')for x in it: p = os.path.basename(x) it.deep = p[0].lower() in "aeiou" print x
这个类提供os.listdir函数的iterator版本。这样做的好处是可以控制遍历的深度,从效率上也不必一下把所有的目录都列出来,遍历一个处理一个即可。
相关内容
- Python 正则表达式(re模块)操作指南,pythonre,原文出处:
- python使用126发邮件代码,python126发邮件,写了个用smtpl
- python读写文件方法介绍,python读写介绍,open 打开文件使
- 动态修改python系统路径,动态python路径,默认情况下py
- Python RGB 和HSV颜色相互转换,pythonhsv,Python RGB 和
- python对MySqldb模块的简单封装代码,pythonmysqldb封装,#!/
- python使用pymongo连接MongoDB,pymongomongodb,本文是一个Pyth
- django-redis-cache:用Redis作django的缓存层,redisdjango,djan
- python实现的守护进程(Daemon),pythondaemon,def createDa
- python多线程Ping网段,python多线程ping,import sysim
评论关闭