本文介绍用python实现的搜索本地文本文件内容的小程序。从而学习Python I/O方面的知识。代码如下:
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文件所在的目录中
#待搜索