2013-03-11 187 views
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中的子进程?

谢谢!

+0

我对你的目标是什么尚不清楚。你是否试图解压目录中的所有文件?等同于:'gunzip * .gz'?你有没有使用gzip模块的具体反对意见? – 2013-03-11 14:29:08

+0

该目录包含压缩和解压缩文件。我需要在一个进程中处理两个进程,所以我的想法是(1)首先运行目录,(2)选择压缩文件并解压缩到新文件(3),然后执行第二次运行来处理。不知道这是否是最好的方式,虽然 – frequent 2013-03-11 14:31:05

+1

回复:反对'gzip',是不是,gzip非常慢 - 就像上面提到的[这里](http://codebright.wordpress.com/2011/03/ 139分之25/)? – frequent 2013-03-11 14:32:21

回答

2

这应该阅读日志子目录中的每个文件的第一行,解压缩的要求:

#!/usr/bin/env python 

import glob 
import gzip 
import subprocess 

for f in glob.glob('logs/*'): 
    if f.endswith('.gz'): 
    # Open a compressed file. Here is the easy way: 
    # file = gzip.open(f, 'rb') 
    # Or, here is the hard way: 
    proc = subprocess.Popen(['zcat', f], stdout=subprocess.PIPE) 
    file = proc.stdout 
    else: 
    # Otherwise, it must be a regular file 
    file = open(f, 'rb') 

    # Process file, for example: 
    print f, file.readline() 
+0

啊。感谢您的澄清:-) – frequent 2013-03-11 14:50:53