1. 程式人生 > >python直接按行讀取gz壓縮檔案中的文字檔案的資料

python直接按行讀取gz壓縮檔案中的文字檔案的資料

之前寫了一個從日誌檔案中(txt檔案)提取特定的日誌,寫入mysql資料庫的指令碼,由於日誌太大,維護人員把日誌打包壓縮成了tar.gz格式。

之前txt檔案單個檔案超過2G,把單個txt檔案打包壓縮成一個tar.gz檔案了。所以我的python指令碼也需要修改。(伺服器centos6.3)

本來想過一個方案,就是把tar.gz解壓出來,然後再讀取,讀取完成後再把這個解壓出來的檔案刪除掉,這個方案不是不可行,但不是很好,一個大檔案的解壓縮比較慢,另一個解壓後比較佔伺服器磁碟。

後來發現另一個方案,直接按行讀取gz壓縮檔案中的文字檔案的資料。

這個是我windows下的測試指令碼:

import os
import os.path
import gzip


def read_gz_file(path):
    if os.path.exists(path):
        with gzip.open(path, 'r') as pf:
            for line in pf:
                yield line
    else:
        print('the path [{}] is not exist!'.format(path))

con = read_gz_file('c:\\1.gz')
if getattr(con, '__iter__', None):
    for line in con:
        print(line)

strZipFile = 'c:\\1.gz'
strDstFile = 'c:\\2'
file   =   gzip.GzipFile(strZipFile,   "r")
outFile   =   open(strDstFile   , "w ")
outFile.write(file.read())
outFile.close()


附件是1.gz檔案

執行結果:

sdfasfda


asdfasdf






asdfasdf


adsfadf