yunshichen

我相信人生是值得活的,尽管人在一生中必须遭受痛苦,卑劣,残酷,不幸和死亡的折磨,我依然深信如此.但我认为人生不一定要有意义,只是对一些人而言,他们可以使人生有意义. ---J 赫胥黎

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



posted on 2010-03-07 16:42 Chenyunshi 阅读(1084) 评论(0)  编辑 收藏 引用 所属分类: Python2.5/2.6

只有注册用户登录后才能发表评论。
<2010年3月>
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

导航

统计

常用链接

留言簿(7)

随笔分类

随笔档案

文章分类

相册

搜索

最新评论

阅读排行榜

评论排行榜