If I have the contents of a zipfile in a Python string, can I decompress it without writing it to a file?

前端 未结 2 832
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 05:31

I\'ve written some Python code that fetches a zip file from the web and into a string:

In [1]: zip_contents[0:5]
Out[1]: \'PK\\x03\\x04\\x14\'
相关标签:
2条回答
  • 2020-12-31 05:38

    Wrap your string in a cStringIO object. It looks, acts, and quacks like a file object, but resides in memory.

    0 讨论(0)
  • 2020-12-31 05:52

    zipfile.ZipFile accepts any file-like object, so you can use StringIO (2.x) or BytesIO (3.x):

    try:
      from cStringIO import StringIO
    except:
      from StringIO import StringIO
    import zipfile
    
    fp = StringIO('PK\x03\x04\x14')
    zfp = zipfile.ZipFile(fp, "r")
    
    0 讨论(0)
提交回复
热议问题