Python,在内存中写入zip到文件

标签 python zip stringio

如何将内存中的压缩文件写入文件?

# Create in memory zip and add files
zf = zipfile.ZipFile(StringIO.StringIO(), mode='w',compression=zipfile.ZIP_DEFLATED)
zf.writestr('file1.txt', "hi")
zf.writestr('file2.txt', "hi")

# Need to write it out
f = file("C:/path/my_zip.zip", "w")
f.write(zf)  # what to do here? Also tried f.write(zf.read())

f.close()
zf.close()

最佳答案

StringIO.getvalue StringIO 的返回内容:

>>> import StringIO
>>> f = StringIO.StringIO()
>>> f.write('asdf')
>>> f.getvalue()
'asdf'

或者,您可以使用 seek 更改文件的位置:

>>> f.read()
''
>>> f.seek(0)
>>> f.read()
'asdf'

尝试以下操作:

mf = StringIO.StringIO()
with zipfile.ZipFile(mf, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
    zf.writestr('file1.txt', "hi")
    zf.writestr('file2.txt', "hi")

with open("C:/path/my_zip.zip", "wb") as f: # use `wb` mode
    f.write(mf.getvalue())

关于Python,在内存中写入zip到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18457678/

相关文章:

异步函数的 Python 类型提示作为函数参数

python - 函数不打印所有偶数?

python - 即使脚本只运行一次,Pypy JIT 也会提高速度?

java - 如何使用 Java 解压目录中所有受密码保护的 zip 文件

python - 向用户提供 Excel(xlsx) 文件以供在 Django(Python) 中下载

python - tensorflow 错误: Consider casting elements to a supported type

c++ - C++ 中的 Zip 目录

file - zip 文件和图像可以存储在 AppFabric 缓存中吗

Ruby 写入内存中的文件(实际上不是写入文件)

python - PIL.Image.open() 给出 IOError : cannot identify image file