我在.bz2文件中工作很长时间了。要将.bz2文件解压缩/解压缩到特定的文件夹中,我一直使用以下函数:
destination_folder = 'unpacked/'
def decompress_bz2_to_folder(input_file):
unpackedfile = bz2.BZ2File(input_file)
data = unpackedfile.read()
open(destination_folder, 'wb').write(data)最近,我获得了一个带有.xz (不是.tar.xz)和.zst扩展名的文件列表。我糟糕的研究技能告诉我,前者是lzma2压缩,后者是Zstandard。
但是,我找不到一种简单的方法将这些档案的内容解压缩到文件夹中(就像我对.bz2文件所做的那样)。
我如何才能:
.xz (lzma2)文件的内容解压缩到文件夹中?.zst (Zstandard)文件的内容解压缩到文件夹中?重要注意:我正在解压非常大的文件,所以如果解决方案考虑到任何潜在的内存错误,那就太好了。
发布于 2019-03-20 12:38:44
可以使用模块解压缩LZMA数据,只需使用该模块打开文件,然后使用shutil.copyfileobj()有效地将解压缩数据复制到输出文件中,而不会遇到内存问题:
import lzma
import pathlib
import shutil
def decompress_lzma_to_folder(input_file):
input_file = pathlib.Path(input_file)
with lzma.open(input_file) as compressed:
output_path = pathlib.Path(destination_dir) / input_file.stem
with open(output_path, 'wb') as destination:
shutil.copyfileobj(compressed, destination)Python标准库还没有对Zstandard压缩的任何支持,您可以使用zstandard (由Mozilla和Mercurial项目的IndyGreg编写)或zstd;后者可能对您的需求来说太基本了,而zstandard提供了一个专门适合读取文件的流API。
我在这里使用zstandard库从它实现的复制API中获益,它允许您同时解压缩和复制,类似于shutil.copyfileobj()的工作方式:
import zstandard
import pathlib
def decompress_zstandard_to_folder(input_file):
input_file = pathlib.Path(input_file)
with open(input_file, 'rb') as compressed:
decomp = zstandard.ZstdDecompressor()
output_path = pathlib.Path(destination_dir) / input_file.stem
with open(output_path, 'wb') as destination:
decomp.copy_stream(compressed, destination)https://stackoverflow.com/questions/55184290
复制相似问题