萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python zlib 壓縮與解壓縮字串/檔案實戰

zlib 是 Python 內建的 DEFLATE 壓縮庫,本文示範字串壓縮、CRC32 校驗、檔案讀寫完整流程,適用於大型文字資料傳輸與儲存優化。

核心程式碼

import zlib

str1 = """Dallas Cowboys football practice at Valley Ranch was delayed on Wednesday for nearly two hours. One of the players, while on his way to the locker room happened to look down and notice a suspicious looking, unknown white powdery substance on the practice field. The coaching staff immediately suspended practice while the FBI was called in to investigate. After a complete field analysis, the FBI determined that the white substance unknown to the players was the goal line. Practice was resumed when FBI Special Agents decided that the team would not be likely to encounter the substance again."""

print('-' * 70)
print(str1)
print('-' * 70)

crc_check1 = zlib.crc32(str1.encode())  # Py3 需 bytes
print("crc before zip =", crc_check1)
print("Length of original str1 =", len(str1))

# 壓縮
zstr1 = zlib.compress(str1.encode())
print("Length of zipped str1 =", len(zstr1))

# 寫入檔案
filename = 'Dallas.zap'
with open(filename, 'wb') as fout:
    fout.write(zstr1)
print("done writing", filename)

# 讀回解壓
with open(filename, 'rb') as fin:
    zstr2 = fin.read()

str2 = zlib.decompress(zstr2).decode()
print('-' * 70)
print(str2)
print('-' * 70)

crc_check2 = zlib.crc32(str2.encode())
print("crc after unzip =", crc_check2, "(check sums should match)")

關鍵點解析

  • 編碼/解碼:Python 3 zlib.compress/decompress 僅接受 bytes,字串需 .encode()/.decode()。
  • CRC32:zlib.crc32 回傳有號 32-bit 整數,可用於完整性驗證。
  • 壓縮率:範例中原文 ~500 字元壓縮後約 300 字節,文字類資料通常 50-70% 壓縮率。
  • 檔案模式:必須用 'wb'/'rb' 二進制模式,避免 Windows 換行符轉換損壞資料。

進階:串流壓縮 zlib.compressobj

處理超大檔案或網路串流時,避免一次性載入記憶體:

compressor = zlib.compressobj(level=6)
with open('big.txt', 'rb') as fin, open('big.zlib', 'wb') as fout:
    while chunk := fin.read(8192):
        fout.write(compressor.compress(chunk))
    fout.write(compressor.flush())

解壓對應 zlib.decompressobj()。

替代方案對比

模組演算法壓縮率速度適用場景
zlibDEFLATE中快通用、標準庫無依賴
gzipDEFLATE + header中快檔案儲存、HTTP 壓縮
bz2BWT高慢離線歸檔
lzmaLZMA最高最慢極致壓縮、軟體發布包
copyright © 萬盛學電腦網 all rights reserved