博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 文件中字符串过滤,并将结果输出到另一个文件中(源码)
阅读量:6890 次
发布时间:2019-06-27

本文共 2439 字,大约阅读时间需要 8 分钟。

    本来想使用Python读取源文件,并使用正则表达式的方式过滤。过程中发现文件编码的问题老是搞不定,就先写个简易版本用于过滤日志文件中感兴趣的行,然后将结果输出到另一个文件中。

    功能:1、输入源文件路径;2、输入希望保存的文件路径; 3、输入希望过滤的词组,也就是满足这些词组中的任何一个都将视作匹配;

    源码如下:

#!/usr/bin/python # -*- coding: UTF-8 -*- import os #import re import time 'readTextFile.py--read and display text file' # 格式化成2016-03-20 11:45:39形式 #print time.strftime("%Y%m%d%H%M%S_log", time.localtime()) #get source file name while True:     fsrcname = raw_input('Please input the file to read:')     if not os.path.exists(fsrcname):         print "Error : '%s' isn't exists." % fsrcname     else:         print "success : '%s' is exists." % fsrcname         break while True:     fdestpath = raw_input('Please input the dest file path to output:')     if not os.path.isdir(fdestpath):         print "Error : '%s' isn't exists." % fdestpath     else:         print "success : '%s' is ok." % fdestpath         break filterstr = []   #word to match while True:     restr = raw_input('Please input the word to match for the lines in log,input :q to quit:')     if restr == ':q':         print "\r\n matching ...,please wait"         break     elif restr == '':         print "Please input valid word to match"     else:         filterstr.append(restr) all = [] try:     fobj = open(fsrcname,'r')     lines = fobj.readlines() except:     print("*** file open error" ) else: #display the contents of the file to the screen.     for eachline in lines:         for eachword in filterstr:             m = eachline.find(eachword)             # if m is not None:             if m >= 0:                 # print m.group()                 all.append(eachline)                 break     fobj.close() if all is not None:     destfilename = time.strftime("%Y%m%d%H%M%S", time.localtime())     destfilename = destfilename + '.log'     if fdestpath.endswith('\\') or fdestpath.endswith('/'):         fdestpath = fdestpath + destfilename     else:         fdestpath = fdestpath + '\\'+ destfilename     print "filter file complete, now the output the result to the '%s' " % fdestpath     try:         fobj = open(fdestpath,'w')     except:         print("*** file open error")     else:         #display the contents of the file to the screen.         for eachline in all:             fobj.writelines(eachline)         fobj.close()         print "file output success, filepath is '%s' " % fdestpath else:     print "filter file fail, no match "

转载于:https://www.cnblogs.com/honorplus/p/8280284.html

你可能感兴趣的文章
javascript总结02
查看>>
创建windows服务
查看>>
C++文件操作(fstream)
查看>>
用main函数传参做简单的计算器的代码
查看>>
python中struct.unpack的用法
查看>>
体绘制(Volume Rendering)概述之4:光线投射算法(Ray Casting)实现流程和代码(基于CPU的实现)...
查看>>
Python实践之(七)逻辑回归(Logistic Regression)
查看>>
PAT (Advanced Level) 1107. Social Clusters (30)
查看>>
【开源社群系统研发日记五】ThinkSNS+ 是如何计算字符显示长度的
查看>>
Nodejs日志管理log4js
查看>>
python获取昨日日期
查看>>
海康威视 - 萤石云开放平台 js 版
查看>>
关于分销平台
查看>>
剑指offer---12-**--数值的整数次方
查看>>
PAT - L2-010. 排座位(并查集)
查看>>
Python 学习笔记 - 线程(线程锁,信标,事件和条件)
查看>>
大数据技术服务商个推获4亿人民币D轮融资
查看>>
Git的详细使用教程
查看>>
iOS实现类似苹果手机原生的锁屏界面(数字密码)
查看>>
[vue] 表单输入格式化,中文输入法异常
查看>>