Python 检索目录下所有文件中包含指定字符串的文件

来源:互联网 发布:网络直播培训 编辑:程序博客网 时间:2024/05/29 02:58

http://blog.csdn.net/authorzhh/article/details/8933758

#!/usr/bin/env python# 1.py# use UTF-8# Python 3.3.0# 检索目录下所有文件中包含指定字符串的文件import osimport re# 枚举dirPath目录下的所有文件def ListFiles(dirPath):#beginfileList = []for root, dirs, files in os.walk(dirPath):# 注意os.walk的功能#beginfor fileObj in files:#beginfileList.append(os.path.join(root, fileObj))#end#endreturn fileList#enddef FindString(filePath, regex):#beginfileObj = open(filePath, 'r')for eachLine in fileObj:#beginif re.search(regex, eachLine, re.I):#beginprint(fileObj)#打印文件对象break#end#end#enddef main():#beginfileDir = "F:" + os.sep + "aaa"# 查找F:\aaa 目录下regex = 'include'# 包含include 的文件fileList = ListFiles(fileDir)print(fileList)for fileObj in fileList:#beginFindString(fileObj, regex)#endos.system("pause")#endif __name__ == '__main__':#beginmain()#end# 输出:# <_io.TextIOWrapper name='F:\\aaa\\1.cpp' mode='r' encoding='cp936'># <_io.TextIOWrapper name='F:\\aaa\\2.h' mode='r' encoding='cp936'># <_io.TextIOWrapper name='F:\\aaa\\3.c' mode='r' encoding='cp936'># <_io.TextIOWrapper name='F:\\aaa\\4.h' mode='r' encoding='cp936'># <_io.TextIOWrapper name='F:\\aaa\\5.cpp' mode='r' encoding='cp936'># <_io.TextIOWrapper name='F:\\aaa\\6.h' mode='r' encoding='cp936'># <_io.TextIOWrapper name='F:\\aaa\\我.cpp' mode='r' encoding='cp936'># 遇到的问题有# 如果做枚举到的文件不是文本文件, 例如rar文件, 就会有异常产生