Python工具箱系列(四十)

发布时间 2023-08-22 16:11:09作者: 西安衍舆航天

使用gzip对数据进行压缩

这是python提供的压缩模块,便于用户对数据、文件进行压缩。功能类似于 GNU 应用程序gzip和gunzip。以下代码压缩一段字节流。

import gzip

# 压缩一段英文
originstr = 'The World Health Organization officially declared on Saturday that the current multi-country monkeypox outbreak outside of the traditional endemic areas in Africa has already turned into a public health emergency of international concern (PHEIC).'
print(len(originstr))
str_compression = gzip.compress(originstr.encode('utf-8'))
print(len(str_compression))
print(str_compression)
decompress_str = gzip.decompress(str_compression)
print(decompress_str)
print(decompress_str.decode('utf-8'))

使用gzip可以直接将数据写入压缩文件中,gzip压缩文件可以像普通文件一样进行打开、写入的操作如下所示。

import gzip

def creategzip():
    info = '核聚变其实就是较轻的原子核在高温高压下聚合成较重的原子核,宇宙中的每一颗恒星都是一个天然的“核聚变反应堆”,在自身重力的挤压下,恒星的核心就会形成高温高压的环境,从而为核聚变提供了条件。原子核的原子序数越高,其发生核聚变的条件也就越高,而恒星核心的温度和压强是与恒星的质量成正比的,因此宇宙中的那些质量较低的恒星是聚变不出什么花样的。'
    
    with gzip.open(r'd:\dev\demo.txt.gz','wb') as out:
        out.write(info.encode('utf8'))
        
def readgzip():
    with gzip.open(r'd:\dev\demo.txt.gz','rb') as input:
        result = input.read()
        print(result.decode('utf-8'))
    
creategzip()
readgzip()

在工程应用中,经常有将几个指定的文件压缩后上传到指定服务器的访求。下面的示例代码中,使用超级轻量的shelve数据库来存储目标文件列表。同时使用gzip模块进行文件压缩。

import shelve
import gzip
import shutil
from pathlib import Path


def generate_filelist():
    """
    在shelve数据库中保存要压缩的目标文件列表
    """
    db = shelve.open('targetfiles')
    db["target"] = [r'D:\toolkit\minikube\minikube.exe',
                    r'C:\Users\tianbin\Music\Syml - Wildfire (Piano and Violin Version).mp3']
    db.close()


def compressbyplan():
    """
    打开数据库,获得目标文件列表,将每个列表进行压缩
    """
    with shelve.open("targetfiles") as db:
        filelist = db['target']
        for targetfile in filelist:
            basename = Path(targetfile).name
            with open(targetfile, 'rb') as f_in:
                with gzip.open(f'{basename}.gz', 'wb') as output:
                    shutil.copyfileobj(f_in, output)


generate_filelist()
compressbyplan()

示例代码中,可以方便的将全路径的目标文件名放在shelve数据库中。shelve数据库是python内置的数据库,相当于把字典保存在了文件上,但同时因为有自己的格式,所以不能够像普通的文本文件一样直接查看与修改,从而保证了一定程度的安全性(虽然这个安全性像纸一样薄)。python提供的gzip模块只能够一次处理一个文件,所以使用pathlib库从全路径文件名中提取纯文件名,随后在本地创建压缩文件。