Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python ZIP archive code

Practise writing member data, adding filesystem files under portable names, decoding a member, and verifying an archive.

Intermediate ~12 min read

Challenge 1

Store the supplied text as a member named reports/summary.txt inside the newly opened ZIP archive.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZipFile

with TemporaryDirectory() as folder:
    archive_path = Path(folder) / "reports.zip"
    with ZipFile(archive_path, "w") as archive:
        
    with ZipFile(archive_path) as archive:
        assert archive.read("reports/summary.txt") == b"ready"
    print("member written")

Press Ctrl⌘Enter to check your answer

Challenge 2

Add the existing source file to the archive under the relative member name tables/input.csv.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZipFile

with TemporaryDirectory() as folder:
    root = Path(folder)
    source = root / "input.csv"
    source.write_text("id\n1\n", encoding="utf-8")
    archive_path = root / "data.zip"
    with ZipFile(archive_path, "w") as archive:
        
    with ZipFile(archive_path) as archive:
        assert archive.namelist() == ["tables/input.csv"]
    print("portable name stored")

Press Ctrl⌘Enter to check your answer

Challenge 3

Read the named ZIP member and decode its UTF-8 bytes into a Python string.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZipFile

with TemporaryDirectory() as folder:
    path = Path(folder) / "message.zip"
    with ZipFile(path, "w") as archive:
        archive.writestr("message.txt", "Hello")
    with ZipFile(path) as archive:
        message = 
        assert message == "Hello"
    print(message)

Press Ctrl⌘Enter to check your answer

Challenge 4

Verify the ZIP members by checking their CRC/header data and assert that no bad member was found.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZipFile

with TemporaryDirectory() as folder:
    path = Path(folder) / "archive.zip"
    with ZipFile(path, "w") as archive:
        archive.writestr("a.txt", "a")
        archive.writestr("b.txt", "b")
    with ZipFile(path) as archive:
        
        assert result is None
    print("integrity check finished")

Press Ctrl⌘Enter to check your answer