實(shí)習(xí)期間,服務(wù)器的一位師兄讓我?guī)兔φ硪幌路?wù)器的log數(shù)據(jù),最終我用Python實(shí)現(xiàn)了數(shù)據(jù)的提取并將其用Excel格式導(dǎo)出。下面是我Python實(shí)現(xiàn)的源碼,可以自動(dòng)遍歷某一文件目錄下的所有文本文件,并將總的數(shù)據(jù)導(dǎo)出到Excel文件中,導(dǎo)出為Excel格式這樣就比較方便統(tǒng)計(jì)了。
//實(shí)現(xiàn)將目錄下所有文件格式為.txt的文件進(jìn)行遍歷統(tǒng)計(jì),如果是別的格式直接將下面的.txt改為你所需要的格式后綴就可以了,比較方便。
//過(guò)程就是先將所有的文件中的內(nèi)容提取出來(lái)寫(xiě)入到一個(gè)新文件中,然后再?gòu)男挛募刑崛?shù)據(jù),最后將數(shù)據(jù)寫(xiě)入到Excel文件中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
from pyExcelerator import * import os currentpath = os.getcwd() testlog = open ( 'test.mak' , 'w' ) os.mkdir(r 'Excel' ) print "currentpath: " ,currentpath for file in os.listdir(currentpath): if os.path.isfile(os.path.join(currentpath, file )) = = True : if file .find( '.txt' )> 0 : / / 如果是別的格式直接將下面的.txt改為你所需要的格式后綴就可以了 file_ = open ( file , 'r' ) content = file_.read() file_.close() testlog.write( content ) print 1 os.popen( 'log_parse.exe test.mak >> shuju.log' ) print 2 for _file in os.listdir(currentpath): if os.path.isfile(os.path.join(currentpath,_file)) = = True : if _file.find( '.log' )> 0 : work = Workbook() works = work.add_sheet( 'Sheet1' ) print 3 file_object = open (_file) for i in range ( 0 , 2 ): works.col(i).width = 10000 i = 0 for line in file_object: line = line.rstrip( '\n' ) print 4 if not line.split(): i = i + 1 if line.strip(): array = line.split( ':' ) lineleft = array[ 0 ] lineright = array[ 1 ] works.write(i, 0 ,lineleft) works.write(i, 1 ,lineright) i = i + 1 _file = _file.rstrip( '.log' ) _file = 'Excel\%s.xls' % _file work.save(_file) |
//其中的print 1 2 3 4 是我打的log如果不想要可以直接刪掉。 使用該P(yáng)ython實(shí)現(xiàn)時(shí)直接將上面代碼保存到 test.py的文件中就行了。
另外中間使用到了一個(gè)c++的提取可執(zhí)行文件log_parse.exe,放在下面了。使用時(shí)將其與test.py放在同一目錄下就可以了。
如果想方便的話(huà)可以建一個(gè).bat文件寫(xiě)成命令行的形式,直接點(diǎn)擊一下就可以自動(dòng)完成所有的工作了,如下:
echo
python test.py
我自己的實(shí)現(xiàn)是大約150M文件跑了一分半的時(shí)間出結(jié)果,我認(rèn)為還比較理想。
以上這篇python腳本實(shí)現(xiàn)數(shù)據(jù)導(dǎo)出excel格式的簡(jiǎn)單方法(推薦)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。