python 文件过滤器

python实用技巧 : Filtering os.walk


'''
Created on Mar 7, 2010
@author: Diego
需求: 得到某个目录下, 符合过滤条件的文件夹/文件.
实现: 将os.walk再次包装.
TODO: 不知道本程序的做法, 和传统的逐个目录列举的方法, 哪个效率更高. 待测试.
 '''
 import   os
 import   os.path
os.path.sep
 =  "  /  "
path 
 =     "  /media/dev/project/google_codes/srgjs  "
EXCLUDE_DIR_LIST 
 =   [  "  .SVN  "  ,  "  CVS  "  ]
EXCLUDE_FILE_LIST 
 =   [  "  .CVSIGNORE  "  ]
 def   is_parent_exclude(parentPath,excludeDirList):
    ss
 =  parentPath.split(  "  /  "  );
    
 for   s   in   ss:
        
 if  (s.upper()   in   excludeDirList):
            
 return   True
    
    
 return   False
 def   filter_walk(targetDirectory,excludeDirList,excludeFileExtList):
    dirList
 =  []
    fileList
 =  []
    
 for   (parent, dirs, files)   in   os.walk(targetDirectory):
        
        
 for   d   in   dirs:
            
 if  (d.upper()   in   excludeDirList):
                
 continue
            
            
 #  To check if one of the parent dir should be excluded.
               if  (is_parent_exclude(parent,excludeDirList)):
                
 continue
            
            dirList.append(parent
 +  "  /  "  +  d)
            
        
        
 for   f   in   files:
            
 if  (f.upper()   in   excludeFileExtList):
                
 continue
            
 #  To check if one of the parent dir should be excluded.
               if  (is_parent_exclude(parent,excludeDirList)):
                
 continue
            
            fileList.append(parent
 +  "  /  "  +  f)
    
    
 return   (dirList,fileList)            
 #  test
 dirs,files   =   filter_walk(path,EXCLUDE_DIR_LIST,EXCLUDE_FILE_LIST)
 for   d   in   dirs:
    
 print   d
 for   f   in   files:
    
 print   f

 

 

转自:http://reader.youdao.com/sharelite?itemId=3844466130777511435&method=viewSharedItemThroughLink&sharedBy=-1137845767117085734

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值