2

我在 Python 的第二周,我被困在一个压缩/解压缩日志文件的目录中,我需要对其进行解析和处理。

目前我正在这样做:

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 答案(此处)和博文(此处) “缝合”在一起

但是,它似乎不起作用,因为我的测试文件是 2.5GB,并且脚本已经咀嚼了 10 分钟以上,而且我不确定我所做的是否正确。

问题:
如果我不想使用 GZIP 模块并且需要逐块解压缩(实际文件大于 10GB),如何在 Python 中使用 zcat 和 subprocess 解压缩并保存到文件?

谢谢!

4

1 回答 1

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()
于 2013-03-11T14:49:35.720 回答