当前位置: 首页 >> 程序设计 >> 用Python遍历文件并搜索文件内容源代码
 

用Python遍历文件并搜索文件内容源代码

作者:      来源:http://blog.csdn.net/foyuan     发表时间:2007-07-30     浏览次数:      字号:    

上一次用Python的2种方法遍历文件,这次参考了一下Python Promgramming  3rd 里面的代码,用os.path.walk来遍历文件,并且搜索文件里面的内容

search_content.py

import os, sys
listonly 
= False
skipexts 
= ['.gif''.exe''.pyc''.o''.a','.dll','.lib','.pdb','.mdb']        # ignore binary files
     
def visitfile(fname, searchKey):                       # for each non-dir file
    global fcount, vcount                              
      
try:
        
if not listonly:
            
if os.path.splitext(fname)[1in skipexts:
                
pass
            
elif open(fname).read().find(searchKey) != -1:
                
print'%s has %s' % (fname, searchKey)
                fcount 
+= 1
    
exceptpass
    vcount 
+= 1 
    
def visitor(args, directoryName,filesInDirectory):     # called for each dir 
    for fname in filesInDirectory:                   
        fpath 
= os.path.join(directoryName, fname)    
        
if not os.path.isdir(fpath):                   
            visitfile(fpath,args)
     
def searcher(startdir, searchkey):
    
global fcount, vcount
    fcount 
= vcount = 0
    os.path.walk(startdir, visitor, searchkey)
     
if __name__ == '__main__':
    root
=raw_input("type root directory:")
    key
=raw_input("type key:")
    searcher(root,key)
    
print 'Found in %d files, visited %d' % (fcount, vcount)

windows调试通过

责任编辑 webmaster

 
 
 
 
 
评论更多>>
 
 
 
发表
 
姓名: QQ:
性别: MSN:
E-mail: 主页:
评分: 1 2 3 4 5
评论内容:
验证码:
  
  • 请遵守《互联网电子公告服务管理规定》及中华人民共和国其他各项有关法律法规。
  • 严禁发表危害国家安全、损害国家利益、破坏民族团结、破坏国家宗教政策、破坏社会稳定、侮辱、诽谤、教唆、淫秽等内容的评论 。
  • 用户需对自己在使用本站服务过程中的行为承担法律责任(直接或间接导致的)。
  • 本站管理员有权保留或删除评论内容。
  • 评论内容只代表网友个人观点,与本网站立场无关。
  •