我想尝试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中都会发生.我错过了什么?