提问人:Ben 提问时间:10/14/2023 更新时间:10/14/2023 访问量:48
现有文件上的 Python 内存中 GZIP
Python in-memory GZIP on existing file
问:
我有一个现有文件的情况。我想使用 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())
此代码将获取现有文件,创建一个压缩版本并将其写回文件系统。第二个块获取压缩文件,打开它并获取 base 64 编码版本。
有没有办法使它更优雅地压缩内存中的文件并在内存中检索 base64 编码的字符串?
答:
2赞
Barmar
10/14/2023
#1
使用 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()))
评论
0赞
Ben
10/14/2023
非常好。正是我想要的。
评论