设为首页 加入收藏

TOP

使用Python查找目录下特定后缀名的文件
2015-08-31 21:25:02 来源: 作者: 【 】 浏览:41
Tags:使用 Python 查找 目录 特定 后缀 文件

目标:使用Python查找目录下特定后缀名的文件


经常会遇到在目录下过滤特定后缀名的文件的需求。自己总结下面两个方法:


第一种方法、比较常规:代码如下


#!/usr/bin/python
?
def endWith(s,*endstring):
? ? ? ? array = map(s.endswith,endstring)
? ? ? ? if True in array:
? ? ? ? ? ? ? ? return True
? ? ? ? else:
? ? ? ? ? ? ? ? return False
?
if __name__ == '__main__':
? ? ? ? import os
? ? ? ? s = os.listdir('/root/')
? ? ? ? f_file = []
? ? ? ? for i in s:
? ? ? ? ? ? ? ? if endWith(i,'.txt','.py'):
? ? ? ? ? ? ? ? ? ? ? ? print i,



执行结果如下:



第二种方法:个人比较倾向这种方法,这种方法可定制性更强,代码如下:


#!/usr/bin/python
def endWith(*endstring):
? ? ? ? ends = endstring
? ? ? ? def run(s):
? ? ? ? ? ? ? ? f = map(s.endswith,ends)
? ? ? ? ? ? ? ? if True in f: return s
? ? ? ? return run
?
if __name__ == '__main__':
? ? ? ? import os
?
? ? ? ? list_file = os.listdir('/root')
? ? ? ? a = endWith('.txt','.py')
? ? ? ? f_file = filter(a,list_file)
? ? ? ? for i in f_file: print i,



执行结果如下:



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python:在指定目录下查找满足条.. 下一篇Android开发学习之Fragment解析

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: