Chinaunix首页 | 论坛 | 博客
  • 博客访问: 907323
  • 博文数量: 75
  • 博客积分: 1216
  • 博客等级: 少尉
  • 技术积分: 1998
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-11 16:20
个人简介

优秀是一种习惯

文章分类

全部博文(75)

文章存档

2014年(1)

2013年(29)

2012年(45)

分类: Python/Ruby

2013-02-05 17:34:41

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

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


#!/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,


执行结果如下:

阅读(30623) | 评论(4) | 转发(0) |
给主人留下些什么吧!~~

闲着无聊_me2014-09-22 09:45:41

第二个代码有问题,比如我要查找后缀名为.lua的文件,然后建一个a.lua.txt的文本,那么这个txt也会输出

tntsjc2014-09-11 10:43:20

小白新人请教一下执行到a = endWith('.txt','.py')时,没有执行def run(s)后的代码而是直接return run了?

那片依然海2013-10-30 20:13:36

noiplee:很不错

好久之前写的了,现在再看看,感觉很陌生,不像是自己写的。。哈哈

回复 | 举报

noiplee2013-10-29 15:28:11

很不错