现有文件上的 Python 内存中 GZIP

标签 python file encoding io gzip

我遇到的情况是我有一个现有文件。我想使用 gzip 压缩该文件并获取该文件的 base64 编码,并使用该字符串进行后续操作,包括作为 API 调用中数据的一部分发送。

我有以下代码,可以正常工作:

import base64
import gzip


base64_string_to_use_later = None
with open('C:\\test.json', 'rb') as orig_file:
   with gzip.open('C:\\test.json.gz', 'wb') as zipped_file:
        zipped_file.writelines(orig_file)
        
with gzip.open('C:\\test.json.gz', 'rb') as zipped_file:
        base64_string_to_use_later = base64.b64encode(zipped_file.read())
    

此代码将获取现有文件,创建压缩版本并将其写回文件系统。第二个 block 获取压缩文件,打开它并获取 Base 64 编码版本。

有没有办法让这个更优雅地压缩内存中的文件并检索内存中的base64编码字符串?

最佳答案

使用gzip.compress()压缩内存中的数据而不是写入文件。

import base64
import gzip

with open('C:\\test.json', 'rb') as orig_file:
    base64_string_to_use_later = base64.b64encode(gzip.compress(orig_file.read()))

关于现有文件上的 Python 内存中 GZIP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77290205/

相关文章:

python - 检查所有输入是否在 pysimplegui 中都有值

python - 使用 for 循环附加多个 pandas 数据帧但返回空数据帧

python - 如何使用多个 subprocess.check_output 并避免非零退出状态 67

java - 创建一个包含增量值的新文件

c# - 如何从 txt 文件中正确读取瑞典语字符

python - 在 OpenCV 和 Python 中控制视频流的对比度和亮度

django - 如何编写批处理文件以自动启动 Django Web 服务器

C++文件流

encoding - 什么是字符编码,为什么要打扰

当尝试使用日语编码调用 wget 时,Python 表现得很奇怪