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

use*_*003 14 python zip stringio

如何将内存zipfile写入文件?

# 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()
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 32

StringIO.getvalue返回内容StringIO:

>>> import StringIO
>>> f = StringIO.StringIO()
>>> f.write('asdf')
>>> f.getvalue()
'asdf'
Run Code Online (Sandbox Code Playgroud)

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

>>> f.read()
''
>>> f.seek(0)
>>> f.read()
'asdf'
Run Code Online (Sandbox Code Playgroud)

试试以下:

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())
Run Code Online (Sandbox Code Playgroud)


use*_*167 8

修改python3的falsetru答案

1)用io.StringIO代替StringIO.StringIO

Python3中的StringIO

2)使用b"abc"代替"abc"

python 3.5:TypeError:写入文件时需要一个类似字节的对象,而不是“ str”

3)编码为二进制字符串 str.encode(s, "utf-8")

在Python 3中将字符串转换为字节的最佳方法?

import zipfile
import io
mf = io.BytesIO()

with zipfile.ZipFile(mf, mode="w",compression=zipfile.ZIP_DEFLATED) as zf:

    zf.writestr('file1.txt', b"hi")

    zf.writestr('file2.txt', str.encode("hi"))
    zf.writestr('file3.txt', str.encode("hi",'utf-8'))


with open("a.txt.zip", "wb") as f: # use `wb` mode
    f.write(mf.getvalue())
Run Code Online (Sandbox Code Playgroud)

这对于gzip也应该起作用:如何gzip在Python中压缩字符串?

  • 如果 Python 的版本不那么混乱的话,Python 将会是一个非常好的语言。应该有一种方法可以检测 Py3 有效的答案...... (2认同)