使用Python在Windows上连接压缩的gz文件

4
有没有一种在Windows上使用Python以内存占用少的方式来将gzipped文件连接起来而不需要解压缩它们的方法?
根据这个回答中的评论,这应该很简单:
cat file1.gz file2.gz file3.gz > allfiles.gz

但是如何在Windows上使用Python完成这个任务呢?

4个回答

8

只需将内容写入同一文件即可。

with open(..., 'wb') as wfp:
  for fn in filenames:
    with open(fn, 'rb') as rfp:
      shutil.copyfileobj(rfp, wfp)

1

你不需要使用Python将多个文件复制到一个文件夹中。你可以使用标准的Windows“复制”功能来完成:

copy file1.gz /b + file2.gz /b + file3.gz /b allfiles.gz

或者,简单来说:
copy *.gz /b allfiles.gz

但是,如果你想使用Python,Ignacio的回答是更好的选择。


你忘记了加号和反斜杠b。 - Ignacio Vazquez-Abrams
1
你在allfiles.gz之前多了一个不必要的+,这会导致file1.gz被覆盖。
"如果省略目标,则文件将合并并存储在列表中第一个文件的名称下。" 来源
- Stefan
你说得对。感谢您对细节的关注。话虽如此,理解文件中 /b 的含义确实很难理解。 - Erik A. Brandstadmoen

1
如果。
cat file1.gz file2.gz file3.gz > allfiles.gz

如果这个有效,那么这个也应该有效:

works, then this should work too:

fileList = ['file1.gz', 'file2.gz', 'file3.gz']
destFilename = 'allfiles.gz'

bufferSize = 8  # Adjust this according to how "memory efficient" you need the program to be.

with open(destFilename, 'wb') as destFile:
    for fileName in fileList:
        with open(fileName, 'rb') as sourceFile:
            chunk = True
            while chunk:
                chunk = sourceFile.read(bufferSize)
                destFile.write(chunk)

这将把输入文件截断为缓冲区的大小。 - Ignacio Vazquez-Abrams
哎呀,你说得对 - 忘记加上 while 循环来获取整个文件了 - 已经修改了,谢谢。 - Brionius
内部循环可以缩短为 for chunk in iter(lambda: sourceFile.read(bufferSize), ''): destFile.write(chunk)。此外,请记住,PEP 8建议使用下划线命名法而不是驼峰命名法。 - user4815162342

0

幸运的是,gzipped文件可以通过cat命令直接串联起来,但不幸的是,在标准库中似乎没有明显的Python命令可以做到这一点(至少在gzip中)。然而,我只是简单地看了一下。可能有一些库可以实现这个。

尽管如此,使用标准库完成这个任务的方法是使用subprocess调用cat

from subprocess import check_call
command = "cat {} {} > {}".format(file1_path, file2_path, output_name)
check_call(command.split())  # Check call takes a list

为了将其推广到任意数量的输入,您可以执行以下操作:

inputs = ['input1', 'input2', ... 'input9001']
output_name = 'output.gz'

command = "".join(['cat ', '{} ' * len(inputs), '> {out}'])
_call_ = command.format(*inputs, out=output_name).split()

check_call(_call_)

我希望这对某人有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接