python实现根据文件关键字进行切分为多个文件的示例

时间:2018-12-10
今天小编就为大家分享一篇python实现根据文件关键字进行切分为多个文件的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

来源:在工作过程中,需要统计一些trace信息,也就是一些打点信息,而打点是通过关键字进行的,因此对一个很大的文件进行分析时,想把两个打点之间的内容单独拷贝出来进行分析。

#!/usr/bin/env python
#__*__ coding: utf-8 __*__
import re
import linecache
 
def fileParse():
 inputfile = input('Input SourcFile:') ##输入源文件,如A.txt
 fp = open(inputfile, 'r')
 
 number =[]
 lineNumber = 1
 keyword = input('Slice Keyword:') ##输入你要切分的关键字
 outfilename = input('Outfilename:')##输出文件名,如out.txt则写out即可,后续输出的文件是out0.txt,out1.txt...
 
 for eachLine in fp:  
  m = re.search(keyword, eachLine) ##查询关键字
  if m is not None:
   number.append(lineNumber) #将关键字的行号记录在number中
  lineNumber = lineNumber + 1
 size = int(len(number))
 for i in range(0,size-1):
  start = number[i]
  end = number[i+1]
  destLines = linecache.getlines(inputfile)[start+1:end-1] #将行号为start+1到end-1的文件内容截取出来
  fp_w = open(outfilename + str(i)+'.txt','w') #将截取出的内容保存在输出文件中
  for key in destLines:
   fp_w.write(key)
  fp_w.close()
 
if __name__ == "__main__":
 fileParse()

以上这篇python实现根据文件关键字进行切分为多个文件的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。