Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create zip file object from bytestring in Python?

I have a bytestring. It's guaranteed that it's a representation of a zip file in bytes. How can I create a zip file object in Python, knowing this bytestring?

like image 886
Anton Hulikau Avatar asked Oct 02 '15 14:10

Anton Hulikau


1 Answers

Use io.BytesIO to construct a file-like object, and then pass that object to the ZipFile constructor.

z = bytes([
0x50, 0x4B, 0x03, 0x04, 0x0A, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7A, 0x52, 0x42, 0x47, 0x20, 0x30,
0x3A, 0x36, 0x06, 0x00, 0x00, 0x00, 0x06, 0x00,
0x00, 0x00, 0x09, 0x00, 0x1C, 0x00, 0x68, 0x65,
0x6C, 0x6C, 0x6F, 0x2E, 0x74, 0x78, 0x74, 0x55,
0x54, 0x09, 0x00, 0x03, 0x97, 0xA0, 0x0E, 0x56,
0x97, 0xA0, 0x0E, 0x56, 0x75, 0x78, 0x0B, 0x00,
0x01, 0x04, 0x31, 0x04, 0x00, 0x00, 0x04, 0x31,
0x04, 0x00, 0x00, 0x68, 0x65, 0x6C, 0x6C, 0x6F,
0x0A, 0x50, 0x4B, 0x01, 0x02, 0x1E, 0x03, 0x0A,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7A, 0x52, 0x42,
0x47, 0x20, 0x30, 0x3A, 0x36, 0x06, 0x00, 0x00,
0x00, 0x06, 0x00, 0x00, 0x00, 0x09, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0xB4, 0x81, 0x00, 0x00, 0x00, 0x00, 0x68,
0x65, 0x6C, 0x6C, 0x6F, 0x2E, 0x74, 0x78, 0x74,
0x55, 0x54, 0x05, 0x00, 0x03, 0x97, 0xA0, 0x0E,
0x56, 0x75, 0x78, 0x0B, 0x00, 0x01, 0x04, 0x31,
0x04, 0x00, 0x00, 0x04, 0x31, 0x04, 0x00, 0x00,
0x50, 0x4B, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x01, 0x00, 0x4F, 0x00, 0x00, 0x00,
0x49, 0x00, 0x00, 0x00, 0x00, 0x00,])

# Given "z", a bytes object containing a ZIP file,
# extract the data therein
import zipfile
import io

zf = zipfile.ZipFile(io.BytesIO(z), "r")
for fileinfo in zf.infolist():
    print(zf.read(fileinfo).decode('ascii'))
like image 107
Robᵩ Avatar answered Oct 01 '22 02:10

Robᵩ