python 读取文件夹中的文件内容是否包含指定字符串

#coding:utf-8
import os.path
import re

def files(filepath):
	pathdir=os.listdir(filepath)
	for alldir in pathdir:
		child=os.path.join('%s/%s'%(filepath,alldir))
		if os.path.isfile(child):
			readfiel(child)
			continue
		files(child)


filelist=[]
lister=['想要的字符串1','想匹配的字符串2']
def readfiel(filename):
	fopen=open(filename,'r') #读取文件
	fileread=fopen.read() #获取文件内容
	fopen.close()
	for lis in lister:
		if lis in fileread:
			urlfile='字符串:%s,文件路径:%s'%(lis,filename)
			filelist.append(urlfile)

if __name__ == '__main__':
	filenames='D:/yuyue'
	files(filenames)
	for i in filelist:
		print i

猜你喜欢

转载自blog.csdn.net/QQ1752506968/article/details/89880831