Python之gzip模块的使用

Posted 小粉优化大师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python之gzip模块的使用相关的知识,希望对你有一定的参考价值。

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

 1、写压缩gzip文件

技术图片
#!/usr/bin/env python3
# encoding: utf-8

import gzip
import io
import os

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

 测试效果

[root@ mnt]# python3 gzip_write.py 
example.text.gz 包含的大小:56bytes
application/x-gzip; charset=binary

[root@ mnt]# ll
total 12
-rw-r--r-- 1 root root  56 Jan  1 09:16 example.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

import gzip
import io
import os
import hashlib

def get_hash(data):
    """返回md5值"""
    return hashlib.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

运行效果

[root@ mnt]# python3 gzip_compresslevel.py 
Level  Size        Checksum
-----  ----------  ---------------------------------
data   344064      03456cbea4852fa964775f38f03f2f2b
   0   344159        1b9895c8eaa94a0fdc5002d35fd44a93
   1   3333        42f88491459c7a7028da1ffb5f2bdc82
   2   3114        13771e090b90d4692a71079856256191
   3   3114        f822f153e8b6da768f8b84559e75e2ca
   4   1797        41e03538d99b3697db87901537e2577f #4以后最优
   5   1797        6cf8fcb66c90ae9a15e480db852800b4
   6   1797        38064eed4cad2151a6c33e6c6a18c7ec
   7   1797        dab0bd23a4d856da383cda3caea87a82
   8   1797        782dc69ce1d62e4646759790991fb531
   9   1797        6d2d8b1532d1a2e50d7e908750aad446

 3、gzip多行的写入压缩

技术图片
#!/usr/bin/env python3
# encoding: utf-8

import gzip
import io
import itertools

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
,10) #重复写入10次
        )
gzip_writelines.py

运行效果

[root@ mnt]# python3 gzip_writelines.py 

[root@ mnt]# ll
total 12
-rw-r--r-- 1 root root  60 Jan  1 09:41 example_line.txt.gz
-rw-r--r-- 1 root root 369 Jan  1 09:40 gzip_writelines.py

[root@ mnt]# gzip -d example_line.txt.gz 

[root@ mnt]# ll
total 12
-rw-r--r-- 1 root root 140 Jan  1 09:41 example_line.txt
-rw-r--r-- 1 root root 369 Jan  1 09:40 gzip_writelines.py

[root@ mnt]# cat example_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

import gzip
import io

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

运行效果

[root@ mnt]# python3 gzip_read.py 
test gzip content

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

技术图片
#!/usr/bin/env python3
# encoding: utf-8

import gzip
import io

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

运行效果

[root@ mnt]# python3 gzip_seek.py 
读取整个压缩文件的内容
btest gzip content
切片取值: bgzip 
移动指针取值: bgzip 
判断两种取值是否一样: True

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

技术图片
#!/usr/bin/env python3
# encoding: utf-8

import gzip
from io import BytesIO
import binascii

# 获取未压缩的数据
uncompress_data = bThe same line,over and over.
 * 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
[root@ mnt]# python3 gzip_BytesIO.py 
Uncompressed Len: 290
Uncompress Data: bThe same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.

Compressed: 51
Compress Data: b1f8b0800264c0c5e02ff0bc94855284ecc4d55c8c9cc4bd5c92f4b2d5248cc4b510031f4b8424625f5b8008147920222010000
利用未压缩的长度,获取压缩后的数据长度: 290
bThe same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.
The same line,over and over.

 

以上是关于Python之gzip模块的使用的主要内容,如果未能解决你的问题,请参考以下文章

python之模块和包

python之基础篇——模块与包

Apache优化之apache网页压缩

Nginx:17---反向代理之(反向代理服务器的性能调优:缓冲数据缓存数据存储数据压缩数据(gzip模块))

nginx高并发优化之gzip模块配置

如何在 Python 3 中将 CSV 编写器与 GZIP 文件一起使用?