1.把日志状态码为200得请求记录下来
记录信息(ip,访问时间,请求资源)
封装函数再次调用,健壮性try except
#coding=utf-8
import re
def aclog(path,putpath):
result=""
with open(path,"r") as fp:
lines=fp.readlines()
for line in lines:
if "200" in line:
ip=re.search(r"(d{1,3}.){3}d{1,3}",line).group()
time=re.search(r"[.*]",line).group()
url=re.search(r"GET.*(200)",line).group()[:-3]
result=ip+time+url+"
"
with open(putpath,"a+") as fp1:
fp1.write(result)
aclog("e:\accesslog.txt","e:\aclog.txt")
另一种方法:使用split
#encoding=utf-8
def AnalysisLog(filenameget,filenameput):
try:
with open(filenameget) as f:
as1=[i.split() for i in f]
as2=[[i[0],i[3],i[6]] for i in as1 if i[8].startswith("2")]
with open(filenameput,"w") as f:
f.writelines(["".join([" ".join(i),"
"]) for i in as2])
return "success!"
except Exception,e:
return "failed!",str(e)
if __name__=="__main__":
filenameget=ur"e:\get.txt"
filenameput=ur"e.\put.txt"
print AnalysisLog(filenameget,filenameput)
在方法二基础上改善
#encoding=utf-8
def AnalysisLog(filenameget,filenameput):
result=""
try:
with open(filenameget) as f:
for line in f.readlines():
i=line.split()
if "200" in line:
result+=i[0]+i[3]+i[6]+" "
with open(filenameput,"w") as f:
f.write(result)
return "success!"
except Exception,e:#
return "failed!",str(e)
if __name__=="__main__":
filenameget=ur"e:\accesslog.txt"
filenameput=ur"e:\put.txt"
print AnalysisLog(filenameget,filenameput)
def AnalysisLog(filenameget,filenameput):
result=""
try:
with open(filenameget) as f:
for line in f.readlines():
i=line.split()
if "200" in line:
result+=i[0]+i[3]+i[6]+" "
with open(filenameput,"w") as f:
f.write(result)
return "success!"
except Exception,e:#
return "failed!",str(e)
if __name__=="__main__":
filenameget=ur"e:\accesslog.txt"
filenameput=ur"e:\put.txt"
print AnalysisLog(filenameget,filenameput)