目标:使用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,
执行结果如下: