有没有一种在Windows上使用Python以内存占用少的方式来将gzipped文件连接起来而不需要解压缩它们的方法?
根据这个回答中的评论,这应该很简单:
根据这个回答中的评论,这应该很简单:
cat file1.gz file2.gz file3.gz > allfiles.gz
但是如何在Windows上使用Python完成这个任务呢?
cat file1.gz file2.gz file3.gz > allfiles.gz
但是如何在Windows上使用Python完成这个任务呢?
只需将内容写入同一文件即可。
with open(..., 'wb') as wfp:
for fn in filenames:
with open(fn, 'rb') as rfp:
shutil.copyfileobj(rfp, wfp)
你不需要使用Python将多个文件复制到一个文件夹中。你可以使用标准的Windows“复制”功能来完成:
copy file1.gz /b + file2.gz /b + file3.gz /b allfiles.gz
copy *.gz /b allfiles.gz
但是,如果你想使用Python,Ignacio的回答是更好的选择。
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)
for chunk in iter(lambda: sourceFile.read(bufferSize), ''): destFile.write(chunk)
。此外,请记住,PEP 8建议使用下划线命名法而不是驼峰命名法。 - user4815162342幸运的是,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_)
我希望这对某人有所帮助。
allfiles.gz
之前多了一个不必要的+
,这会导致file1.gz
被覆盖。"如果省略目标,则文件将合并并存储在列表中第一个文件的名称下。" 来源 - Stefan