---
title: "python 文件过滤器"
author: "eric_wyf"
date: "2011-10-24T15:36:31Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2011-10-24T15:36:31Z"
id: 1210947
url: "https://eric-wyf.iteye.com/blog/1210947"
---

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](http://reader.youdao.com/sharelite?itemId=3844466130777511435&method=viewSharedItemThroughLink&sharedBy=-1137845767117085734)