使用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 的详细介绍请点这里
Python 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2015-08/121284.htm
今日推荐