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设计】。

相关文章

PyTorch的深度学习入门教程之构建神经网络

前言 本文参考PyTorch官网的教程,分为五个基本模块来介绍PyTorch。为了避免文章过长,这五个模块分别在五篇博文中介绍。 Part3:使用PyTorch构建一个神经网络 神经网络...

Python3 修改默认环境的方法

Mac 环境中既有自带的 Python2.7 也有自己安装的 Python 3.5.1,默认想用 Python3 的环境 1. 添加 Python3 的环境变量 vi ~/.bash...

pygame游戏之旅 游戏中添加显示文字

pygame游戏之旅 游戏中添加显示文字

本文为大家分享了pygame游戏之旅的第5篇,供大家参考,具体内容如下 在游戏中添加显示文字: 这里自己定义一个crash函数接口: def crash(): message_di...

Python正则表达式实现简易计算器功能示例

本文实例讲述了Python正则表达式实现简易计算器功能。分享给大家供大家参考,具体如下: 需求:使用正则表达式完成一个简易计算器。 功能:能够计算简单的表达式。 如:1*2*((1+...

python使用opencv在Windows下调用摄像头实现解析

python使用opencv在Windows下调用摄像头实现解析

这篇文章主要介绍了python使用opencv在Windows下调用摄像头实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 环境...