Jam*_*ams 6 python gzip python-3.x
我想模仿gzip -d <file.gz>Python脚本中的行为.
压缩的GZIP文件被解压缩并写为具有与原始GZIP文件相同的文件名的文件,而不带.gz扩展名.
file.abc.gz - > file.abc
使用gzip库如何做到这一点并不明显,文档中的所有示例都是用于压缩数据数组,而我还没有通过Google找到一个很好的例子.任何人都可以建议吗?在此先感谢您的帮助.
编辑:我已经尝试使用tarfile模块,但不幸的是它不起作用,我认为因为GZIP文件不是用tar创建的.
# get the zipped file's contents list, extract the file
with tarfile.TarFile(local_zipped_filename) as tar_file:
# list the contents, make sure we only extract the expected named file
members = tar_file.getmembers()
for member in members:
if member.name == filename_unzipped:
members_to_extract = [member]
tar_file.extractall(path=destination_dir, members=members_to_extract)
break # we've extracted our file, done
Run Code Online (Sandbox Code Playgroud)
import gzip, shutil
with gzip.open('file.abc.gz', 'r') as f_in, open('file.abc', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
Run Code Online (Sandbox Code Playgroud)
该gzip模块提供类似文件的对象,其中包含gzip文件的解压缩内容; 该shutil模块提供了一个方便的帮助程序,用于将内容从一个类文件对象复制到另一个文件.
这是官方文档中给出的示例的简单反转:
如何GZIP压缩现有文件的示例:
Run Code Online (Sandbox Code Playgroud)import gzip import shutil with open('/home/joe/file.txt', 'rb') as f_in: with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out)