简体   繁体   English

在 Python 中将类文件对象添加到 Zip 文件

[英]Adding a file-like object to a Zip file in Python

The Python ZipFile API seems to allow the passing of a file path to ZipFile.write or a byte string to ZipFile.writestr but nothing in between. Python ZipFile API 似乎允许将文件路径传递给ZipFile.write或将字节字符串传递给ZipFile.writestr但两者之间没有任何内容。 I would like to be able to pass a file like object, in this case a django.core.files.storage.DefaultStorage but any file-like object in principle.我希望能够传递一个类似对象的文件,在这种情况下是django.core.files.storage.DefaultStorage但原则上任何类似文件的对象。 At the moment I think I'm going to have to either save the file to disk, or read it into memory.目前我想我要么将文件保存到磁盘,要么将其读入内存。 Neither of these is perfect.这两者都不是完美的。

You are correct, those are the only two choices.你是对的,这是唯一的两个选择。 If your DefaultStorage object is large, you may want to go with saving it to disk first;如果您的DefaultStorage对象很大,您可能希望先将其保存到磁盘; otherwise, I would use:否则,我会使用:

zipped = ZipFile(...)
zipped.writestr('archive_name', default_storage_object.read())

If default_storage_object is a StringIO object, it can use default_storage_object.getvalue() .如果default_storage_objectStringIO对象,则可以使用default_storage_object.getvalue()

While there's no option that takes a file-like object, there is an option to open a zip entry for writing (ZipFile.open).虽然没有采用类文件对象的选项,但可以选择打开 zip 条目进行写入 (ZipFile.open)。 [doc] [文档]

import zipfile
import shutil
with zipfile.ZipFile('test.zip','w') as archive:
    with archive.open('test_entry.txt','w') as outfile:
        with open('test_file.txt','rb') as infile:
            shutil.copyfileobj(infile, outfile)

You can use your input stream as the source instead, and not have to copy the file to disk first.您可以使用输入流作为源,而不必先将文件复制到磁盘。 The downside is that if something goes wrong with your stream, the zip file will be unusable.缺点是如果您的流出现问题,则 zip 文件将无法使用。 In my application, we bypass files with errors, so we end up getting a local copy of the file anyway to ensure integrity and keep a usable zip file.在我的应用程序中,我们绕过有错误的文件,因此无论如何我们最终都会获得文件的本地副本,以确保完整性并保留可用的 zip 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM