如何在内存中创建包含多个文件和子文件夹的 zip 存档?

mat*_*ick 2 python zip python-zipfile

以下命令运行,但导致文件解压失败:

import io
import zipfile

b = io.BytesIO()
zf = zipfile.ZipFile(b, mode='w')
zf.writestr('a/b.txt', 'look here')
zf.writestr('a/c.txt', 'look there')
open('here.zip', 'wb').write(b.getbuffer())
Run Code Online (Sandbox Code Playgroud)

然后测试:

$ unzip here.zip
Archive:  here.zip
  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of here.zip or
        here.zip.zip, and cannot find here.zip.ZIP, period.
Run Code Online (Sandbox Code Playgroud)

缺什么?

更新:

这似乎现在有效,不确定它是否已最大压缩?

import io
import zipfile

b = io.BytesIO()
zf = zipfile.ZipFile(b, mode='w')
zf.writestr('a/b.txt', 'look here')
zf.writestr('a/c.txt', 'look there')
zf.close()
open('here.zip', 'wb').write(b.getbuffer())
Run Code Online (Sandbox Code Playgroud)

Kar*_*ran 7

在您的代码中,您需要在将数据写入 zip 文件后关闭该文件。下面是示例代码。

import io
import zipfile
b = io.BytesIO()
zf = zipfile.ZipFile(b, mode='w')
zf.writestr('a/b.txt', 'look here')
zf.writestr('a/c.txt', 'look there')
zf.close()
open('here.zip', 'wb').write(b.getbuffer())
Run Code Online (Sandbox Code Playgroud)