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

yipeiwu_com6年前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中将正则过滤的内容输出写入到文件中的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python在windows下实现备份程序实例

很多书籍里面讲的Python备份都是在linux下的,而在xp上测试一下也可以执行备份功能,代码都差不多相同,就是到执行打包的时候是不一样的。而且要用到winrar,其他的压缩文件也是一...

使用Python导出Excel图表以及导出为图片的方法

使用Python导出Excel图表以及导出为图片的方法

本篇讲下如何使用纯python代码将excel 中的图表导出为图片。这里需要使用的模块有win32com、pythoncom模块。 网上经查询有人已经写好的模块pyxlchart,具体代...

Python3日期与时间戳转换的几种方法详解

日期和时间的相互转换可以利用Python内置模块 time 和 datetime 完成,且有多种方法供我们选择,当然转换时我们可以直接利用当前时间或指定的字符串格式的时间格式。 获取当前...

5款Python程序员高频使用开发工具推荐

5款Python程序员高频使用开发工具推荐

很多Python学习者想必都会有如下感悟:最开始学习Python的时候,因为没有去探索好用的工具,吃了很多苦头。后来工作中深刻体会到,合理使用开发的工具的便利和高效。今天,我就把Pyth...

python去除空格和换行符的实现方法(推荐)

一、去除空格 strip() "   xyz   ".strip()      &nb...