Writing then reading in-memory bytes (BytesIO) gives a blank result

后端 未结 2 1514
夕颜
夕颜 2020-12-13 23:45

I wanted to try out the python BytesIO class.

As an experiment I tried writing to a zip file in memory, and then reading the bytes back out of that zip file. So inst

2条回答
  •  -上瘾入骨i
    2020-12-14 00:21

    How about we write and read gzip content in the same context like this? If this approach is good and works for you anyone reading this, please +1 for this answer so that I know this approach right and works for other people?

    #!/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)
            g.close()
        gzipped_content = myio.getvalue()
    
    print(gzipped_content)
    print(content == gzip.decompress(gzipped_content))
    

提交回复
热议问题