我想在Python中将多个。gz(而不是tar.gz)文件合并为一个。tar.gz文件。
我创建了临时文件,逐个解压缩它们并使用Tarfile#addfile。我可以做我想做的事,但我觉得效率很低。
我想使用一个缓冲区。有什么有效的方法吗?
谢谢。
目前的情况是这样的:
def make_tmp(gz_file):
with open(gz_file) as rt:
with open("tmp/" + gz_file, mode="wb") as w:
while True:
buf = rt.read(65535)
if not buf:
break
w.write(buf)
gz_files = os.listdir("target_gz")
for gz in gz_files:
make_tmp(gz)
with tarfile.open("combined.tar.gz", mode="w:gz") as tw:
for tmp in os.listdir("tmp")
tw.add(tmp)
我希望它是这样的:
with tarfile.open("combined.tar.gz", mode="w:gz") as tw:
for gz in os.listdir("target_gz"):
with open(gz, mode="rb") as r:
while True:
buf = rt.read(65535)
if not buf:
break
tw.write(gz[:12], buf) # I want to add a file, cut "target_file" and store it
目录树:
.
├── target_gz/
│ ├── foo.gz
│ └── bar.gz
├── tmp/
│ ├── foo.file
│ └── bar.file
├── run.py
└── combined.tar.gz
应该可以:
import pathlib
import tarfile
with tarfile.open('combined.tar.gz', 'w') as tw:
for filename in pathlib.Path('./target_gz').glob('*.gz'):
print(filename)
tw.add(filename)