2
我在Python的第二週,我被困在一個壓縮/解壓縮日誌文件的目錄,我需要解析和處理。如何測試gzip的文件目錄並使用zcat在Python中解壓縮gzip文件?
目前我在做這個:
import os
import sys
import operator
import zipfile
import zlib
import gzip
import subprocess
if sys.version.startswith("3."):
import io
io_method = io.BytesIO
else:
import cStringIO
io_method = cStringIO.StringIO
for f in glob.glob('logs/*'):
file = open(f,'rb')
new_file_name = f + "_unzipped"
last_pos = file.tell()
# test for gzip
if (file.read(2) == b'\x1f\x8b'):
file.seek(last_pos)
#unzip to new file
out = open(new_file_name, "wb")
process = subprocess.Popen(["zcat", f], stdout = subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
if process.poll() != None:
break;
output = io_method(process.communicate()[0])
exitCode = process.returncode
if (exitCode == 0):
print "done"
out.write(output)
out.close()
else:
raise ProcessException(command, exitCode, output)
我已經 「縫合」 在一起使用這些SO答案(here)和相關博客文章(here)
但是,它似乎不工作,因爲我的測試文件是2.5GB,腳本一直在咀嚼10分鐘以上,而且我不確定我所做的是否正確無誤。
問:
如果我不想用gzip模塊,需要去壓縮塊逐塊(實際文件> 10GB),我該如何解壓和保存使用ZCAT到文件和Python中的子進程?
謝謝!
我對你的目標是什麼尚不清楚。你是否試圖解壓目錄中的所有文件?等同於:'gunzip * .gz'?你有沒有使用gzip模塊的具體反對意見? – 2013-03-11 14:29:08
該目錄包含壓縮和解壓縮文件。我需要在一個進程中處理兩個進程,所以我的想法是(1)首先運行目錄,(2)選擇壓縮文件並解壓縮到新文件(3),然後執行第二次運行來處理。不知道這是否是最好的方式,雖然 – frequent 2013-03-11 14:31:05
回覆:反對'gzip',是不是,gzip非常慢 - 就像上面提到的[這裏](http://codebright.wordpress.com/2011/03/ 139分之25/)? – frequent 2013-03-11 14:32:21