网络编程
位置:首页>> 网络编程>> Python编程>> python实现根据文件关键字进行切分为多个文件的示例

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

作者:xqn2017  发布时间:2021-03-04 16:35:19 

标签: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()

来源:https://www.cnblogs.com/xqn2017/p/8021675.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com