實習期間,服務器的一位師兄讓我幫忙整理一下服務器的log數據,最終我用Python實現了數據的提取并將其用Excel格式導出。下面是我Python實現的源碼,可以自動遍歷某一文件目錄下的所有文本文件,并將總的數據導出到Excel文件中,導出為Excel格式這樣就比較方便統計了。
//實現將目錄下所有文件格式為.txt的文件進行遍歷統計,如果是別的格式直接將下面的.txt改為你所需要的格式后綴就可以了,比較方便。
//過程就是先將所有的文件中的內容提取出來寫入到一個新文件中,然后再從新文件中提取數據,最后將數據寫入到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如果不想要可以直接刪掉。 使用該Python實現時直接將上面代碼保存到 test.py的文件中就行了。
另外中間使用到了一個c++的提取可執行文件log_parse.exe,放在下面了。使用時將其與test.py放在同一目錄下就可以了。
如果想方便的話可以建一個.bat文件寫成命令行的形式,直接點擊一下就可以自動完成所有的工作了,如下:
echo
python test.py
我自己的實現是大約150M文件跑了一分半的時間出結果,我認為還比較理想。
以上這篇python腳本實現數據導出excel格式的簡單方法(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。