目标:使用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:在指定目录下查找满足条件的文件 http://www.linuxidc.com/Linux/2015-08/121283.htm
Python2.7.7源码分析 http://www.linuxidc.com/Linux/2015-08/121168.htm
无需操作系统直接运行 Python 代码 http://www.linuxidc.com/Linux/2015-05/117357.htm
CentOS上源码安装Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm
《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm
《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm
Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm
在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm
Python 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm
Python 的详细介绍:请点这里
Python 的下载地址:请点这里
本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-08/121284.htm
