首页  > 教育解读  > python怎样解压二进制gz文件

python怎样解压二进制gz文件

2025-05-08 21:36:54
面试李组长
面试李组长已认证

面试李组长为您分享以下优质知识

在Python中解压二进制`.gz`文件,推荐使用`gzip`模块或`shutil`模块。以下是具体方法:

一、使用`gzip`模块解压单个二进制文件

```python

import gzip

def un_gz(file_name):

with gzip.open(file_name, 'rb') as f_in:

with open(file_name[:-3], 'wb') as f_out:

f_out.write(f_in.read())

示例

un_gz('binary.gz') 生成 binary.txt

```

说明:通过`gzip.open`以二进制读取模式打开压缩文件,再写入到去掉`.gz`后缀的新文件中。

二、使用`shutil`模块批量解压二进制文件

```python

import shutil

import os

def gunzip_shutil(source_filepath, dest_filepath, block_size=65536):

with gzip.open(source_filepath, 'rb') as s_file, open(dest_filepath, 'wb') as d_file:

shutil.copyfileobj(s_file, d_file, block_size)

def loop_dir(path):

for file in os.listdir(path):

if file.endswith('.gz'):

gunzip_shutil(os.path.join(path, file), os.path.join(path, file[:-3]))

示例

main(['path/to/gz/files'])

```

说明:`shutil.copyfileobj`分块读取压缩文件并写入新文件,适合处理大文件。`loop_dir`函数可递归解压目录下所有`.gz`文件。

三、使用`tarfile`模块解压`.tar.gz`文件(二进制归档)

```python

import tarfile

def extract_tar_gz(file_name, dest_path='temp'):

with tarfile.open(file_name, 'r:gz') as tar:

tar.extractall(path=dest_path)

示例

extract_tar_gz('example.tar.gz') 解压到 temp 目录

```

说明:`tarfile`模块支持解压`.tar.gz`等二进制归档文件,`extractall`方法可指定目标路径。

总结:解压二进制`.gz`文件时,优先选择`gzip`模块处理单个文件,或`shutil`模块批量处理。若需解压`.tar.gz`归档,则使用`tarfile`模块。