python搜索文件内容_python实现搜索文本文件内容脚本

import os

#根据文件扩展名判断文件类型

def endWith(s,*endstring):

array = map(s.endswith,endstring)

if True in array:

return True

else:

return False

#将全部已搜索到的关键字列表中的内容保存到result.log文件中

def writeResultLog(allExistsKeywords):

#行分隔符

ls = os.linesep

#结果日志文件名

logfilename = "result.log" #相对路径,文件在.py文件所在的目录中

try:

fobj = open(logfilename,'w')

except IOError,e:

print "*** file open error:",e

else:

fobj.writelines(['%s%s' % (keyword,ls) for keyword in allExistsKeywords])

fobj.close()

#搜索指定关键字是否在指定的文件中存在

def searchFilesContent(dirname):

#从searchkeywords.txt文件中初始化待搜索关键字列表

filename = "searchkeywords.txt" #相对路径,文件在.py文件所在的目录中

#待搜索关键字列表

allSearchKeywords=[] #遍历文件当前行已搜索到的关键字列表

existsKeywordsThisLine=[] #全部已搜索到的关键字列表

allExistsKeywords=[]

try:

fobj = open(filename,'r');

except IOError,e:

print "*** file open error:",e

else:

for eachLine in fobj:

allSearchKeywords.append(eachLine.strip('n')); #使用strip函数去除每行的换行符

fobj.close();

#从excludekeywords.txt文件中初始化要排除的搜索关键字列表

filename = "excludekeywords.txt" #相对路径,文件在.py文件所在的目录中

#要排除的搜索关键字列表

allExcludedKeywords=[] try:

fobj = open(filename,'r');

except IOError,e:

print "*** file open error:",e

else:

for eachLine in fobj:

allExcludedKeywords.append(eachLine.strip('n')); #使用strip函数去除每行的换行符

fobj.close();

#从全部已搜索到的关键字列表排除掉不用搜索的关键字

for excluedkw in allExcludedKeywords:

if(excluedkw in allSearchKeywords):

allSearchKeywords.remove(excluedkw);

#遍历打开所有要在其中搜索内容的文件,若待搜索关键字列表为空,则不再继续遍历

for root,dirs,files in os.walk(dirname):

for file in files:

if endWith(file,'.java','.xml','.properties'): #只在扩展名为.java/.xml/.properties文件中搜索

#打开文件

filename = root + os.sep + file #绝对路径

filename = filename.replace("","\") #将路径中的单反斜杠替换为双反斜杠,因为单反斜杠可能会导致将路径中的内容进行转义了,replace函数中""表示单反斜杠,"\"表示双反斜杠

try:

fobj = open(filename,'r');

except IOError,e:

print "*** file open error:",e

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值