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)")
zlib.compress/decompress 僅接受 bytes,字串需 .encode()/.decode()。zlib.crc32 回傳有號 32-bit 整數,可用於完整性驗證。'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()。
| 模組 | 演算法 | 壓縮率 | 速度 | 適用場景 |
|---|---|---|---|---|
| zlib | DEFLATE | 中 | 快 | 通用、標準庫無依賴 |
| gzip | DEFLATE + header | 中 | 快 | 檔案儲存、HTTP 壓縮 |
| bz2 | BWT | 高 | 慢 | 離線歸檔 |
| lzma | LZMA | 最高 | 最慢 | 極致壓縮、軟體發布包 |