python gzip压缩

Python gzip module provides a very simple way to compress and decompress files and work in a similar manner to GNU programs gzip and gunzip.

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

In this lesson, we will study what classes are present in this module which allows us to perform the mentioned operations along with the additional functions it provides.

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

Python gzip模块 (Python gzip module)

This module provides us with the Gzip class which contains some convenience functions like open(), compress() and decompress().

该模块为我们提供了Gzip类,其中包含一些便捷功能,例如open()compress()decompress()

The advantage Gzip class provides us is that it reads and writes gzip files and automatically compresses and decompresses it so that in the program, they looks just like normal File objects.

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

It is important to remember that the other formats which are supported by the programs gzip and gunzip are not supported by this module.

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

使用gzip模块 (Using gzip module)

We will now start using the functions we mentioned to perform compression and decompression operations.

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

使用open()编写压缩文件 (Writing Compressed Files with open())

We will start with the open() function which creates an instance of GzipFile and open the file with wb mode to write to a compressed file:

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

import gzip
import io
import osoutput_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))

Let’s see the output for this program:

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

Python Gzip write to compressed file

Python Gzip写入压缩文件

To write to the compressed file, we first opened it in the wb mode and wrapped the GzipFile instance with a TextIOWrapper from the io module to encode Unicode text to bytes which is suitable for compression.

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

将多行写入压缩文件 (Writing multiple lines to compressed file)

This time, we will use almost the same script as we used above but we will write multiple lines to it. Let’s look at the code how this can be achieved:

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

import gzip
import io
import os
import itertoolsoutput_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('JournalDev, same line again and again!.\n', 10))os.system('gzcat jd_example.txt.gz')

Let’s see the output for this program:

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

Writing multiple lines to compressed file

将多行写入压缩文件

读取压缩数据 (Reading Compressed Data)

Now that we’re done with the file writing process, we can read data form the compressed file as well. We will now use another file mode, which is rb, read mode.

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

import gzip
import io
import osread_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())

Let’s see the output for this program:

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

Read compressed file

读取压缩文件

Notice that there was nothing special we did here with Gzip apart form passing it a different file mode. The reading process is done by the TextIOWrapper which uses as File object which is provided by the gzip module.

请注意,我们在这里对Gzip进行分离并没有什么特别的形式,它将不同的文件模式传递给了它。 读取过程由TextIOWrapper完成,该TextIOWrapper用作gzip模块提供的File对象。

阅读流 (Reading Streams)

Another big advantage gzip module offers is that it can be used to wrap other types of streams as well so they can make use of compression too. This is extremely useful when you want to transmit a lot of data over web sockets.

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

Let’s see how we can compress and decompress stream data:

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

import gzip
from io import BytesIO
import binasciiwrite_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)

Let’s see the output for this program:

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

Read Stream

读取流

Notice that while writing, we didn’t have to provide any length parameters. But this wasn’t the case when we re-read the data. We had to pass the length to read() function explicitly.

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

结论 (Conclusion)

In this lesson, we studied Python gzip module which can be used to read and write to compressed files with a big advantage that the modules makes the compressed file looks like just a normal File object.

在本课程中,我们研究了Python gzip模块,该模块可用于读取和写入压缩文件,这具有很大的优势,即模块使压缩文件看起来就像普通的File对象。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/19827/python-gzip-compress-decompress

python gzip压缩

python gzip压缩_Python gzip –压缩解压缩相关推荐

  1. python zip压缩_Python zip压缩与解压(zipfile模块实例)

    python中提供了文件压缩的zipfile模块. zipfile模块() 用于压缩文件成zip及解压zip文件,模块介绍如下. zipfile.ZipFile(file, mode) open a ...

  2. python gzip模块实现文件压缩的方法

    python gzip模块实现文件压缩的方法 使用gzip格式压缩文件,注意引入gzip包. 代码: 复制代码代码示例: #!/bin/python # #site: www.jbxue.com im ...

  3. python读取和写入 gzip和bz2格式的压缩文件中的数据

    读取.gz压缩格式 # gzip compressionimport gzipwith gzip.open('somefile.gz', 'rt') as f:text = f.read() 读取.b ...

  4. Linux压缩命令gzip、tar、zip的区别和用法

    Linux压缩命令gzip.tar.zip的区别和用法 Linux系统中常用的压缩命令有gzip.tar.zip等. gzip命令是一个压缩文件的工具,常用参数有: -c : 把压缩后的文件输出到标准 ...

  5. asp.net实现GZip压缩和GZip解压

    最近在开发一个网站doc.115sou.com,使用到了GZip压缩技术,经过多次搜索找到asp.net中用GZip对数据压缩和解压缩非常方便,当我第一次拿到这个类的时候却感觉很迷茫,无从下手.主要是 ...

  6. Linux的实际操作:文件目录类实用指令(压缩gzip tar -zcvf和解压缩gunzip tar -zxvf)

    1.gzip   用于压缩文件 (压缩文件后,原文件就会消失自动成为一个新的压缩文件,意思是压缩后不保留原文件) 2.gunzip   用于解压文件 (解压缩后,压缩文件也会自动生成一个未解压文件,解 ...

  7. java gzip rest_RestTemplate与Gzip压缩

    Gzip 是一种压缩算法,服务器经常通过这个算法来压缩响应体,再响应给客户端,从而减少数据体积,提高传输速度.客户端再通过Gzip解压缩,获取到原始的数据.因为需要压缩计算,所以会耗费额外的CPU资源 ...

  8. python读压缩文件内容_Python读写压缩文件的方法

    问题 你想读写一个gzip或bz2格式的压缩文件. 解决方案 gzip 和bz2模块可以很容易的处理这些文件. 两个模块都为 open()函数提供了另外的实现来解决这个问题. 比如,为了以文本形式读取 ...

  9. 压缩命令_linux中压缩文件命令gzip和tar的压缩选项的简单用法

    linux当中压缩命令有多种,比较常用的有gzip gzip的用法很简单,把要压缩的文件或列表跟在命令gzip的后面就可以了. gzip 要压缩的文件 | 列表 gzip file.tar 压缩打包文 ...

最新文章

  1. python中文版-Python3.8.2下载
  2. Ubuntu中启用关闭Network-manager网络设置问题!
  3. CAD2011软件安装资料及教程
  4. SpringCloud分布式事务,版本一:未加事务版本
  5. 读取笔记本的摄像头的原始yuv数据,通过libav(ffmpeg编码)
  6. 蔡司数码视疲劳测试软件_居家办公期间,频繁使用电子数码产品小心患上这种眼病...
  7. csh shell_Shell基础知识
  8. 男孩子一定要注意保护自己!
  9. ENVI的seamless mosaic工具详解
  10. 公式编辑器里面添加空格
  11. 【深度首发】图森未来CEO陈默:我们并非在主机厂上游兜售技术,而是立足下游,做卡车运输业的智能服务商丨Xtecher 封面
  12. docker安装教程
  13. 【MATLAB】图像分割
  14. python之爬取中华诗词网
  15. (TVS)简介(瞬态抑制二极管)参数
  16. applet java_Java applet 类
  17. 安卓投屏大师TC DS如何把手机声音传输到电脑教程
  18. 远程过程调用失败0x800706be
  19. HBase数据库原理介绍
  20. GreenPlum 数据库启动关闭及数据库状态检查

热门文章

  1. HTML+CSS 整站 步骤
  2. 采样干扰十大滤波算法程序大全
  3. [转载] numpy.linalg.matrix_power 计算矩阵的次方
  4. [转载] 【python第四天】 注释和缩进
  5. 高通HAL层之Sensor HAL
  6. maven项目在eclipse中debug
  7. html5 教程网站
  8. 数据结构上机实践第八周项目6- 猴子选大王(数组版)
  9. VScode+远程服务器docker+C/C++ 代码挑战配置
  10. 数据结构笔记(二十三)--哈夫曼树