twa*_*lig 56 python byte gzip bytesio
我想尝试python BytesIO类.
作为一个实验,我尝试写入内存中的zip文件,然后从该zip文件中读取字节.因此gzip
,我传入一个BytesIO
对象,而不是传入一个文件对象.这是整个脚本:
from io import BytesIO
import gzip
# write bytes to zip file in memory
myio = BytesIO()
g = gzip.GzipFile(fileobj=myio, mode='wb')
g.write(b"does it work")
g.close()
# read bytes from zip file in memory
g = gzip.GzipFile(fileobj=myio, mode='rb')
result = g.read()
g.close()
print(result)
Run Code Online (Sandbox Code Playgroud)
但它正在返回一个空bytes
对象result
.这在Python 2.7和3.4中都会发生.我错过了什么?
mgi*_*son 91
seek
在内存文件中写入初始文件后,您需要回到文件的开头...
myio.seek(0)
Run Code Online (Sandbox Code Playgroud)
我们在这样的上下文中编写和读取 gzip 内容怎么样?
#!/usr/bin/env python
from io import BytesIO
import gzip
content = b"does it work"
# write bytes to zip file in memory
gzipped_content = None
with BytesIO() as myio:
with gzip.GzipFile(fileobj=myio, mode='wb') as g:
g.write(content)
gzipped_content = myio.getvalue()
print(gzipped_content)
print(content == gzip.decompress(gzipped_content))
Run Code Online (Sandbox Code Playgroud)