gzip模块作用:

为GNU zip文件提供了一个类似的接口,它使用zlib来压缩和解压数据。

1、写压缩gzip文件

#!/usr/bin/env python3#encoding: utf-8

importgzipimportioimportos

out_file_name= "example.text.gz"with gzip.open(out_file_name,‘wb‘) as output:

with io.TextIOWrapper(output, encoding=‘utf-8‘) as enc:

enc.write(‘test gzip content‘)print(out_file_name, ‘包含的大小:{}bytes‘.format(os.stat(out_file_name).st_size))

os.system(‘file -b --mime {}‘.format(out_file_name))

gzip_write.py

测试效果

[[email protected] mnt]# python3 gzip_write.py

example.text.gz 包含的大小:56bytes

application/x-gzip; charset=binary

[[email protected] mnt]# ll

total12

-rw-r--r-- 1 root root 56 Jan 1 09:16example.text.gz-rw-r--r-- 1 root root 464 Jan 1 09:13 gzip_write.py

2、gzip压缩级别的测试以及适当设置值

#!/usr/bin/env python3#encoding: utf-8

importgzipimportioimportosimporthashlibdefget_hash(data):"""返回md5值"""

returnhashlib.md5(data).hexdigest()#读取文件内容,并且复制1024份出来

data = open(‘content.txt‘, ‘r‘).read() * 1024

#输入文件内容,返回md5值

check_sum = get_hash(data.encode(‘utf-8‘))print(‘Level Size Checksum‘)print(‘----- ---------- ---------------------------------‘)print(‘data {:>5} {}‘.format(len(data), check_sum))for i in range(0, 10):

file_name= ‘compress-level-{}.gz‘.format(i)

with gzip.open(file_name,‘wb‘, compresslevel=i) as output:

with io.TextIOWrapper(output, encoding=‘utf-8‘) as enc:

enc.write(data)

size=os.stat(file_name).st_size

check_sum= get_hash(open(file_name, ‘rb‘).read())print(‘{} {:>4} {}‘.format(i, size, check_sum))

gzip_compresslevel.py

运行效果

[[email protected] mnt]#python3 gzip_compresslevel.py

Level Size Checksum----- ---------- ---------------------------------data34406403456cbea4852fa964775f38f03f2f2b

03441591b9895c8eaa94a0fdc5002d35fd44a931 333342f88491459c7a7028da1ffb5f2bdc822 311413771e090b90d4692a710798562561913 3114f822f153e8b6da768f8b84559e75e2ca4 1797 41e03538d99b3697db87901537e2577f #4以后最优

5 17976cf8fcb66c90ae9a15e480db852800b46 179738064eed4cad2151a6c33e6c6a18c7ec7 1797dab0bd23a4d856da383cda3caea87a828 1797782dc69ce1d62e4646759790991fb5319 1797 6d2d8b1532d1a2e50d7e908750aad446

3、gzip多行的写入压缩

#!/usr/bin/env python3#encoding: utf-8

importgzipimportioimportitertools

with gzip.open(‘example_line.txt.gz‘,‘wb‘) as output:

with io.TextIOWrapper(output,encoding=‘utf-8‘) as enc:

enc.writelines(

itertools.repeat(‘The same line\n‘,10) #重复写入10次

)

gzip_writelines.py

运行效果

[[email protected] mnt]# python3 gzip_writelines.py

[[email protected] mnt]# ll

total12

-rw-r--r-- 1 root root 60 Jan 1 09:41example_line.txt.gz-rw-r--r-- 1 root root 369 Jan 1 09:40gzip_writelines.py

[[email protected] mnt]#gzip -d example_line.txt.gz

[[email protected] mnt]# ll

total12

-rw-r--r-- 1 root root 140 Jan 1 09:41example_line.txt-rw-r--r-- 1 root root 369 Jan 1 09:40gzip_writelines.py

[[email protected] mnt]#catexample_line.txt

The same line

The same line

The same line

The same line

The same line

The same line

The same line

The same line

The same line

The same line

4、读取gzip压缩文件内容

#!/usr/bin/env python3#encoding: utf-8

importgzipimportio

with gzip.open(‘example.text.gz‘, ‘rb‘) as input_file:

with io.TextIOWrapper(input_file, encoding=‘utf-8‘) as dec:print(dec.read())

gzip_read.py

运行效果

[[email protected] mnt]# python3 gzip_read.py

testgzip content

5、读取gzip压缩文件利用seek定位取值

#!/usr/bin/env python3#encoding: utf-8

importgzipimportio

with gzip.open(‘example.text.gz‘, ‘rb‘) as input_file:print(‘读取整个压缩文件的内容‘)

all_data=input_file.read()print(all_data)

expected= all_data[5:10] #切片取值

print(‘切片取值:‘, expected)#将流文件的指针切至起始点

input_file.seek(0)#将流文件的指针切至5的下标

input_file.seek(5)

new_data= input_file.read(5)print(‘移动指针取值:‘, new_data)print(‘判断两种取值是否一样:‘,expected == new_data)

gzip_seek.py

运行效果

[[email protected] mnt]# python3 gzip_seek.py

读取整个压缩文件的内容

b‘test gzip content‘切片取值: b‘gzip‘移动指针取值: b‘gzip‘判断两种取值是否一样: True

6、gzip字节流的处理(ByteIO)的示例

#!/usr/bin/env python3#encoding: utf-8

importgzipfrom io importBytesIOimportbinascii#获取未压缩的数据

uncompress_data = b‘The same line,over and over.\n‘ * 10

print(‘Uncompressed Len:‘, len(uncompress_data))print(‘Uncompress Data:‘, uncompress_data)

buffer=BytesIO()

with gzip.GzipFile(mode=‘wb‘, fileobj=buffer) as f:

f.write(uncompress_data)#获取压缩的数据

compress_data =buffer.getvalue()print(‘Compressed:‘, len(compress_data))print(‘Compress Data:‘, binascii.hexlify(compress_data))#重新读取数据

inbuffer =BytesIO(compress_data)

with gzip.GzipFile(mode=‘rb‘, fileobj=inbuffer) as f:

reread_data=f.read(len(uncompress_data))print(‘利用未压缩的长度,获取压缩后的数据长度:‘, len(reread_data))print(reread_data)

gzip_BytesIO.py

[[email protected] mnt]# python3 gzip_BytesIO.py

Uncompressed Len:290Uncompress Data: b‘The same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\n‘Compressed:51Compress Data: b‘1f8b0800264c0c5e02ff0bc94855284ecc4d55c8c9cc4bd5c92f4b2d5248cc4b510031f4b8424625f5b8008147920222010000‘利用未压缩的长度,获取压缩后的数据长度:290b‘The same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\nThe same line,over and over.\n‘

原文:https://www.cnblogs.com/ygbh/p/12128233.html

python gzip_Python之gzip模块的使用相关推荐

  1. 利用python中的gzip模块压缩和解压数据流和文件

    直接给出源码实现, 分为两种情况: 1.网络连接中的数据流的压缩和解压,或是打开的文件读取一部分 2.打开文件压缩或是解压 #!/usr/bin/env python #encoding: utf-8 ...

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

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

  3. Python第二十天 shutil 模块 zipfile tarfile 模块

    Python第二十天  shutil 模块  zipfile   tarfile 模块 os文件的操作还应该包含移动 复制  打包 压缩 解压等操作,这些os模块都没有提供 shutil 模块 shu ...

  4. Python下使用tarfile模块来实现文件归档压缩与解压

    Python下使用tarfile模块来实现文件归档压缩与解压   部分转自:http://www.diybl.com/course/3_program/python/20110510/555345.h ...

  5. 网络爬虫day1:python中的request模块基本使用

    网络爬虫day1:python中的request模块基本使用 get和post的区别 python运行代码 请求头 get和post的区别 在互联网的世界中,有一个不经常提起但是经常使用的协议:TCP ...

  6. python:XML处理模块

    python:XML处理模块 简介 XML 漏洞 defusedxml 包 简介 用于处理XML的Python接口分组在 xml 包中. 警告 XML 模块对于错误或恶意构造的数据是不安全的. 如果你 ...

  7. Python实战之logging模块使用详解

    用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么了,但是当我需要看大量的地方或者在一个文件中查看的时候,这时候print就不大方便了,所 ...

  8. 【廖雪峰python进阶笔记】模块

    1. 导入模块 要使用一个模块,我们必须首先导入该模块.Python使用import语句导入一个模块.例如,导入系统自带的模块 math: import math 你可以认为math就是一个指向已导入 ...

  9. Python标准库queue模块原理浅析

    Python标准库queue模块原理浅析 本文环境python3.5.2 queue模块的实现思路 作为一个线程安全的队列模块,该模块提供了线程安全的一个队列,该队列底层的实现基于Python线程th ...

  10. Python标准库threading模块Condition原理浅析

    Python标准库threading模块Condition原理浅析 本文环境python3.5.2 threading模块Condition的实现思路 在Python的多线程实现过程中,在Linux平 ...

最新文章

  1. python输出数据到excel-如何使用python将传感器数据输出保存到excel中
  2. PyCharm如何集成PyQt
  3. OpenCV几何变换的实例(附完整代码)
  4. 剖析java中的String之__拼接
  5. 全国计算机二级等级考试项目有什么,全国计算机等级考试二级内容
  6. Coursera机器学习编程作业Python实现(Andrew Ng)—— 2.1 Logistic Regression
  7. 是谁榨干了 Android 设备的电量和流量?!| 极客头条
  8. vc++2010注册表修改
  9. matlab 汽车 仿真,MATLAB编程与汽车仿真应用
  10. CodeForces - 1040B Shashlik Cooking (思维/贪心)
  11. linux查看云锁密码命令,Linux安装云锁
  12. python自测单词软件_还在用背单词App?使用Python开发英语单词自测工具,助你逆袭单词王!...
  13. js:使用amaze select插件
  14. Deep Multimodal Representation Learning(深度多模态表示学习)
  15. 树状数组入门——以洛谷3374为例
  16. 关于斗地主编程的思考
  17. 什么是AUTOSAR规范?
  18. 百度实习两个月小结~
  19. 【STM32技巧】ADC模拟量采集的几种用法
  20. 20170829 过客

热门文章

  1. 中国第一,全球领先的「浪潮」:用智慧计算征服的计算力天下
  2. 2021年全国职业院校技能大赛(中职组)网络安全竞赛正式赛题A模块防火墙部分解析
  3. 5G基站硬件架构及演进研究
  4. 在linux系统下做软raid教程
  5. 时钟系统(NTP子母钟系统)如何为高铁系统保驾护航
  6. Android隐藏app应用图标(隐式启动)
  7. 解决MAC launchpad顽固性图标无法删除问题。
  8. 使用redis缓存技术实现省市区三级联动
  9. 火狐浏览器设置cookie失败_如何启用火狐浏览器的Cookie功能 这些经验不可多得...
  10. 小tips:页面滚动到关闭时的位置与不滚动