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

来源:互联网 发布:东华理工行知分院照片 编辑:程序博客网 时间:2024/05/18 02:26

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

#!/usr/bin/env python# 1.py# use UTF-8# Python 3.3.0# <strong>检索目录</strong>下<strong>所有<strong>文件</strong></strong>中<strong>包含指定字符串</strong>的<strong><strong>文件</strong></strong>import osimport re# 枚举dirPath<strong>目录</strong>下的<strong>所有<strong>文件</strong></strong>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)#打印<strong><strong>文件</strong></strong>对象break#end#end#enddef main():#beginfileDir = "F:" + os.sep + "aaa"# 查找F:\aaa <strong>目录</strong>下regex = 'include'# <strong>包含</strong>include 的<strong><strong>文件</strong></strong>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…………………………………………………………………………<p style="COLOR: red; FONT-SIZE: 16px"><strong>具体:<a target=_blank href="http://www.verydemo.com/demo_c122_i23830.html" target="_blank">http://www.verydemo.com/demo_c122_i23830.html</a></strong></p>
0 0
原创粉丝点击