python中将正则过滤的内容输出写入到文件中

处理过滤Apache日志文件

access_test.log文件内容
27.19.74.143 - - [30/May/2015:17:38:21 +0800] "GET /static/image/smiley/default/sleepy.gif HTTP/1.1" 200 2375
8.35.201.164 - - [30/May/2015:17:38:21 +0800] "GET /static/image/common/pn.png HTTP/1.1" 200 592

过滤目标
60.166.12.170 31/May/2013:00:00:02 /forum.php 200 45780

处理后将内容写入到文件20160205.txt
#!/usr/bin/env python    
# - coding:utf - 8 -*-
import re,sys

with open('access_test.log') as f:
    for line in f:
        parseip = re.search(r'(.*?) - - ', line)
        parsetime = re.search(r' \[(.*?)\] ', line)
        parseurl = re.search(r' "\w+ (.*?) HTTP/', line)
        parsestatus = re.search(r' HTTP/(.*?)" (.*?) ', line)
        parseTraffic = re.search(r'\d+ \d+', line)

        if parseip and parsetime and parseurl and parsestatus and parseTraffic is None:
            continue
        
        output=sys.stdout
        outputfile=open('20160205.txt','a')
        sys.stdout=outputfile
        print parseip.group(1).split('?')[0] + '\t' + parsetime.group(1).split('?')[0] + '\t' + parseurl.group(1).split('?')[0] + '\t' + parsestatus.group(2) + '\t' + parseTraffic.group(0).split(' ')[1]
        outputfile.close()
        sys.stdout=output


import sys
然后在打算把输出数据写入文件的代码之前加上以下代码
output=sys.stdout
outputfile=open(filename,'w')
sys.stdout=outputfile
上面的filename表示输出文件

程序结束或恢复成正常输出时加上以下代码
outputfile.close()
sys.stdout=output
恢复输出为开始保存的正常输出值

你可能感兴趣的:(python中将正则过滤的内容输出写入到文件中)