search
HomeBackend DevelopmentPython Tutorial在Python中使用zlib模块进行数据压缩的教程

Python标准模块中,有多个模块用于数据的压缩与解压缩,如zipfile,gzip, bz2等等。上次介绍了zipfile模块,今天就来讲讲zlib模块。
zlib.compress(string[, level])
zlib.decompress(string[, wbits[, bufsize]])

zlib.compress用于压缩流数据。参数string指定了要压缩的数据流,参数level指定了压缩的级别,它的取值范围是1到9。压缩速度与压缩率成反比,1表示压缩速度最快,而压缩率最低,而9则表示压缩速度最慢但压缩率最高。zlib.decompress用于解压数据。参数string指定了需要解压的数据,wbits和bufsize分别用于设置系统缓冲区大小(window buffer )与输出缓冲区大小(output buffer)。下面用一个例子来演示如何使用这两个方法:
 

#coding=gbk
 
import zlib, urllib
 
fp = urllib.urlopen('http://localhost/default.html')
str = fp.read()
fp.close()
 
#---- 压缩数据流。
str1 = zlib.compress(str, zlib.Z_BEST_COMPRESSION)
str2 = zlib.decompress(str1)
print len(str)
print len(str1)
print len(str2)
 
# ---- 结果
#5783
#1531
#5783

我们也可以使用Compress/Decompress对象来对数据进行压缩/解压缩。zlib.compressobj([level]) 与zlib.decompress(string[, wbits[, bufsize]]) 分别创建Compress/Decompress缩对象。通过对象对数据进行压缩和解压缩的使用方式与上面介绍的zlib.compress,zlib.decompress非常类似。但两者对数据的压缩还是有区别的,这主要体现在对大量数据进行操作的情况下。假如现在要压缩一个非常大的数据文件(上百M),如果使用zlib.compress来压缩的话,必须先一次性将文件里的数据读到内存里,然后将数据进行压缩。这样势必会战用太多的内存。如果使用对象来进行压缩,那么没有必要一次性读取文件的所有数据,可以先读一部分数据到内存里进行压缩,压缩完后写入文件,然后再读其他部分的数据压缩,如此循环重复,只到压缩完整个文件。下面一个例子来演示这之间的区别:
 

#coding=gbk
 
import zlib, urllib
 
fp = urllib.urlopen('http://localhost/default.html')  
# 访问的到的网址。
data = fp.read()
fp.close()
 
#---- 压缩数据流
str1 = zlib.compress(data, zlib.Z_BEST_COMPRESSION)
str2 = zlib.decompress(str1)
print '原始数据长度:', len(data)
print '-' * 30
print 'zlib.compress压缩后:', len(str1)
print 'zlib.decompress解压后:', len(str2)
print '-' * 30
 
#---- 使用Compress, Decompress对象对数据流进行压缩/解压缩
com_obj = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
decom_obj = zlib.decompressobj()
 
str_obj = com_obj.compress(data)
str_obj += com_obj.flush()
print 'Compress.compress压缩后:', len(str_obj)
 
str_obj1 = decom_obj.decompress(str_obj)
str_obj1 += decom_obj.flush()
print 'Decompress.decompress解压后:', len(str_obj1)
print '-' * 30
 
#---- 使用Compress, Decompress对象,对数据进行分块压缩/解压缩。
com_obj1 = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
decom_obj1 = zlib.decompressobj()
chunk_size = 30;
 
#原始数据分块
str_chunks = [data[i * chunk_size:(i + 1) * chunk_size] /
  for i in range((len(data) + chunk_size) / chunk_size)]
 
str_obj2 = ''
for chunk in str_chunks:
  str_obj2 += com_obj1.compress(chunk)
str_obj2 += com_obj1.flush()
print '分块压缩后:', len(str_obj2)
 
#压缩数据分块解压
str_chunks = [str_obj2[i * chunk_size:(i + 1) * chunk_size] /
  for i in range((len(str_obj2) + chunk_size) / chunk_size)]
str_obj2 = ''
for chunk in str_chunks:
  str_obj2 += decom_obj1.decompress(chunk)
str_obj2 += decom_obj1.flush()
print '分块解压后:', len(str_obj2)
 
# ---- 结果 ------------------------
原始数据长度: 5783
------------------------------
zlib.compress压缩后: 1531
zlib.decompress解压后: 5783
------------------------------
Compress.compress压缩后: 1531
Decompress.decompress解压后: 5783
------------------------------
分块压缩后: 1531
分块解压后: 5783

Python手册对zlib模块的介绍比较详细,更具体的应用,可以参考Python手册。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)