如何在不触及磁盘的情况下创建包含目录的内存zip文件?

pth*_*lin 16 python

在python Web应用程序中,我将一些东西打包成zip文件.我想在内存中完全执行此操作,而不需要触摸磁盘.只要我正在创建一个平面目录结构,使用ZipFile.writestr就可以了,但是如何在zip中创建目录呢?

我正在使用python2.4.

http://docs.python.org/library/zipfile.html

pth*_*lin 30

What 'theomega' said in the comment to my original post, adding a '/' in the filename does the trick. Thanks!

from zipfile import ZipFile
from StringIO import StringIO

inMemoryOutputFile = StringIO()

zipFile = ZipFile(inMemoryOutputFile, 'w') 
zipFile.writestr('OEBPS/content.xhtml', 'hello world')
zipFile.close()

inMemoryOutputFile.seek(0)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您使用的是python 3,那么您将需要使用[`BytesIO`](https://docs.python.org/3/library/io.html). (4认同)