Python gzip –压缩解压缩

时间:2020-02-23 14:42:46  来源:igfitidea点击:

Python gzip模块提供了一种非常简单的方式来压缩和解压缩文件,并以类似于GNU程序gzip和gunzip的方式工作。

在本程序中,我们将研究此模块中存在哪些类,这些类使我们能够执行上述操作以及它提供的其他功能。

Python gzip模块

这个模块为我们提供了Gzip类,其中包含一些便利功能,例如open(),compress()和decompress()。

Gzip类提供给我们的好处是,它可以读写gzip文件,并自动对其进行压缩和解压缩,以便在程序中它们看起来像普通的File对象。

重要的是要记住,该模块不支持gzip和gunzip程序支持的其他格式。

使用gzip模块

现在,我们将开始使用我们提到的功能来执行压缩和解压缩操作。

用open()编写压缩文件

我们将从open()函数开始,该函数创建一个GzipFile实例,并以wb模式打开文件以写入压缩文件:

import gzip
import io
import os

output_file_name = 'jd_example.txt.gz'
file_mode = 'wb'

with gzip.open(output_file_name, file_mode) as output:
  with io.TextIOWrapper(output, encoding='utf-8') as encode:
      encode.write('We can write anything in the file here.\n')

print(output_file_name, 
      'contains', os.stat(output_file_name).st_size, 'bytes')
os.system('file -b --mime {}'.format(output_file_name))

让我们看一下该程序的输出:Python Gzip写入压缩文件

要写入压缩文件,我们首先以wb模式打开它,并使用io模块中的TextIOWrapper包装GzipFile实例,以将Unicode文本编码为适合压缩的字节。

将多行写入压缩文件

这次,我们将使用与上面几乎相同的脚本,但是将向其中写入多行。
让我们看一下如何实现此目标的代码:

import gzip
import io
import os
import itertools

output_file_name = 'jd_example.txt.gz'
file_mode = 'wb'

with gzip.open(output_file_name, file_mode) as output:
  with io.TextIOWrapper(output, encoding='utf-8') as enc:
      enc.writelines(
          itertools.repeat('theitroad, same line again and again!.\n', 10)
      )

os.system('gzcat jd_example.txt.gz')

让我们看一下该程序的输出:将多行写入压缩文件

读取压缩数据

现在我们已经完成了文件写入过程,我们也可以从压缩文件中读取数据。
现在,我们将使用另一种文件模式,即rb模式,即读取模式。

import gzip
import io
import os

read_file_name = 'jd_example.txt.gz'
file_mode = 'rb'

with gzip.open(read_file_name, file_mode) as input_file:
  with io.TextIOWrapper(input_file, encoding='utf-8') as dec:
      print(dec.read())

让我们看看该程序的输出:读取压缩文件

请注意,我们在这里使用Gzip分开格式并没有传递任何不同的文件模式,因此没有什么特别的事情。
读取过程是由TextIOWrapper完成的,该TextIOWrapper用作gzip模块提供的File对象。

阅读流

gzip模块提供的另一个大优点是,它也可以用于包装其他类型的流,因此它们也可以利用压缩。
当您想通过Web套接字传输大量数据时,这非常有用。

让我们看看如何压缩和解压缩流数据:

import gzip
from io import BytesIO
import binascii

write_mode = 'wb'
read_mode = 'rb'

uncompressed = b'Reiterated line n times.\n' * 8
print('Uncompressed Data:', len(uncompressed))
print(uncompressed)

buf = BytesIO()
with gzip.GzipFile(mode=write_mode, fileobj=buf) as file:
  file.write(uncompressed)

compressed = buf.getvalue()
print('Compressed Data:', len(compressed))
print(binascii.hexlify(compressed))

inbuffer = BytesIO(compressed)
with gzip.GzipFile(mode=read_mode, fileobj=inbuffer) as file:
  read_data = file.read(len(uncompressed))

print('\nReading it again:', len(read_data))
print(read_data)

让我们看看该程序的输出:

请注意,在编写时,我们不必提供任何长度参数。
但是,当我们重新读取数据时,情况并非如此。
我们必须将长度明确传递给read()函数。