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)
修改python3的falsetru答案
1)用io.StringIO代替StringIO.StringIO
2)使用b"abc"代替"abc"或
python 3.5:TypeError:写入文件时需要一个类似字节的对象,而不是“ str”
3)编码为二进制字符串 str.encode(s, "utf-8")
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中压缩字符串?
| 归档时间: |
|
| 查看次数: |
17523 次 |
| 最近记录: |