Skip to content

Instantly share code, notes, and snippets.

@nakagami
Last active February 28, 2024 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakagami/3616b6af196d53c18360ef22e4d7b284 to your computer and use it in GitHub Desktop.
Save nakagami/3616b6af196d53c18360ef22e4d7b284 to your computer and use it in GitHub Desktop.
Create and Extract zip file example
import io
import zipfile
# Create and extract zip file example
# to file
with zipfile.ZipFile("test.zip", 'w') as z:
z.writestr('aaa/bbb/1.txt', b'aaa')
z.writestr('aaa/ccc/2.txt', b'ccc')
z.writestr('aaa/ccc/3.bin', b'\x00\x01\x02')
# to memory
mf = io.BytesIO()
with zipfile.ZipFile(mf, 'w') as z:
z.writestr('aaa/bbb/1.txt', b'aaa')
z.writestr('aaa/ccc/2.txt', b'ccc')
z.writestr('aaa/ccc/3.bin', b'\x00\x01\x02')
assert mf.getvalue() == open("test.zip", "rb").read()
# extract zip
with zipfile.ZipFile("test.zip") as z:
names = z.namelist()
assert names == ['aaa/bbb/1.txt', 'aaa/ccc/2.txt', 'aaa/ccc/3.bin']
values = []
for name in names:
with z.open(name) as fp:
values.append(fp.read())
assert values == [b'aaa', b'ccc', b'\x00\x01\x02']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment