http://blog.youkuaiyun.com/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 os
import re
# 枚举dirPath<strong>目录</strong>下的<strong>所有<strong>文件</strong></strong>
def ListFiles(dirPath):
#begin
fileList = []
for root, dirs, files in os.walk(dirPath): # 注意os.walk的功能
#begin
for fileObj in files:
#begin
fileList.append(os.path.join(root, fileObj))
#end
#end
return fileList
#end
def FindString(filePath, regex):
#begin
fileObj = open(filePath, 'r')
for eachLine in fileObj:
#begin
if re.search(regex, eachLine, re.I):
#begin
print(fileObj) #打印<strong><strong>文件</strong></strong>对象
break
#end
#end
#end
def main():
#begin
fileDir = "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:
#begin
FindString(fileObj, regex)
#end
os.system("pause")
#end
if __name__ == '__main__':
#begin
main()
#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>