Last active
February 28, 2024 06:56
-
-
Save nakagami/3616b6af196d53c18360ef22e4d7b284 to your computer and use it in GitHub Desktop.
Create and Extract zip file example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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