gpt4 book ai didi

python - 如何在python中直接将文件添加到zip?

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:17 27 4
gpt4 key购买 nike

我是 python 新手。在这里,我的目标是将数据放入 zip 文件中。以下是我编写的代码,其中我将数据写入一个 unzipped_file,然后将 unzipped_file 写入 zipped_file.zip,然后删除解压文件。

import os
import zipfile

##Some code above.............
for some_data in big_data:
with open('unzipped_file', 'a+') as unzipped_f:
unzipped_f.write(some_data)

##Some code in between...........

with zipfile.ZipFile('zipped_file.zip', 'w') as zipped_f:
zipped_f.write("unzipped_file")

os.remove("unzipped_file")

而不是创建一个中间的 unzipped_file。我可以一步直接将我的数据写入 zipped_file 吗?

最佳答案

zipfile.writestr(file_name, bytes)将由 bytes 表示的原始数据写入存档。 file_name 是存档将包含的文件的名称。

with zipfile.ZipFile('zipped_file.zip', 'w') as zipped_f:
zipped_f.writestr("file_name", some_data)

编辑:要将多条数据写入存档中的某个文件,您唯一可以做的就是一次写入所有数据:

with zipfile.ZipFile('zipped_file.zip', 'w') as zipped_f:
zipped_f.writestr("file_name", ''.join(x for x in big_data))

上述方法仅在 big_data 包含字符串时有效。否则,您可以尝试 pickle.dumps(big_data)pickle.dumps(list(big_data))

请注意,big_data 的副本(除非它是生成器)将在内存中构建,然后写入文件。如果不解压缩然后再次压缩,则不可能更新现有 ZipFile 存档中的文件。

关于python - 如何在python中直接将文件添加到zip?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40886234/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com