微商城电商系统开发商,seo免费外链工具,俄罗斯最新军事动态,成立外贸公司的流程使用gzip对数据进行压缩
这是python提供的压缩模块#xff0c;便于用户对数据、文件进行压缩。功能类似于 GNU 应用程序gzip和gunzip。以下代码压缩一段字节流。 import gzip# 压缩一段英文
originstr The World Health Organization officially declared on Saturday that …使用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 gzipdef creategzip():info 核聚变其实就是较轻的原子核在高温高压下聚合成较重的原子核宇宙中的每一颗恒星都是一个天然的“核聚变反应堆”在自身重力的挤压下恒星的核心就会形成高温高压的环境从而为核聚变提供了条件。原子核的原子序数越高其发生核聚变的条件也就越高而恒星核心的温度和压强是与恒星的质量成正比的因此宇宙中的那些质量较低的恒星是聚变不出什么花样的。with gzip.open(rd:\dev\demo.txt.gz,wb) as out:out.write(info.encode(utf8))def readgzip():with gzip.open(rd:\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 Pathdef generate_filelist():在shelve数据库中保存要压缩的目标文件列表db shelve.open(targetfiles)db[target] [rD:\toolkit\minikube\minikube.exe,rC:\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).namewith 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库从全路径文件名中提取纯文件名,随后在本地创建压缩文件。