如何使用zcat在Python中测试文件夹中的gzip文件并解压缩?

2 投票
1 回答
2530 浏览
提问于 2025-04-17 18:41

我现在正在学习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)

这些代码是我参考了一些StackOverflow上的回答(这里)和一些博客文章(这里)拼凑起来的。

但是,这个方法似乎不太奏效,因为我的测试文件有2.5GB,脚本已经运行了超过10分钟,而且我也不太确定我做的是否正确。

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

谢谢!

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()

撰写回答