自学内容网 自学内容网

关于文本压缩传输gzip

import gzip  
import base64  
  
# 假设我们有一个文本文件要读取和压缩  
input_filename = '2.json'  
# 我们将Base64编码的gzip压缩数据写入这个文件  
output_filename = '2.json.base64'  
  
# 读取文本文件内容(假设文件是UTF-8编码的)  
with open(input_filename, 'r', encoding='utf-8') as file:  
    text_content = file.read()  
  
# 将文本内容编码为字节串(UTF-8),然后gzip压缩  
compressed_data = gzip.compress(text_content.encode('utf-8'))  
  
# 将压缩后的数据Base64编码  
base64_encoded = base64.b64encode(compressed_data)  
  
# 注意:base64_encoded现在是字节串,但我们想要将其写入文件作为文本  
# 一种方法是将其解码为Unicode字符串(虽然它只包含ASCII字符)  
# 但更明确的是,我们直接以二进制模式写入字节串  
  
# 将Base64编码的字节串写入文件  
with open(output_filename, 'wb') as file:  
    file.write(base64_encoded)  
  
# 如果你想要将Base64编码的字节串作为文本写入文件(不推荐,但可能有用)  
# 你可以先将其解码为Unicode字符串,但请确保你了解这样做可能引入的复杂性  
# with open(output_filename, 'w') as file:  
#     file.write(base64_encoded.decode('ascii'))

如果原文件是文本,压缩后约为1/4大小

hex头特征

b'\x1f\x8b'

base64开头特征

H4sI


原文地址:https://blog.csdn.net/impish0/article/details/142613576

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!