如何将内存中的压缩文件写入文件?
# 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'
或者,可以使用以下命令更改文件的位置:
>>> 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 - Python,在内存中写入zip到文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18457678/