Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python TAR archive code

Practise creating TAR members, reading member bytes, and extracting with an explicit data filter.

Intermediate ~12 min read

Challenge 1

Add the existing source file to the open TAR archive under the portable member name reports/notes.txt.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory
import tarfile

with TemporaryDirectory() as folder:
    root = Path(folder)
    source = root / "notes.txt"
    source.write_text("ready", encoding="utf-8")
    archive_path = root / "notes.tar"
    with tarfile.open(archive_path, "w") as archive:
        
    with tarfile.open(archive_path) as archive:
        assert archive.getnames() == ["reports/notes.txt"]
    print("portable member name stored")

Press Ctrl⌘Enter to check your answer

Challenge 2

Create and add a TarInfo member containing the supplied bytes without making a source file.

python Your answer
import io
import tarfile
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    archive_path = Path(folder) / "data.tar"
    payload = b"ready"
    member = tarfile.TarInfo("status.txt")
    member.size = len(payload)
    with tarfile.open(archive_path, "w") as archive:
        
    with tarfile.open(archive_path) as archive:
        with archive.extractfile("status.txt") as stream:
            assert stream.read() == payload
    print("member stored")

Press Ctrl⌘Enter to check your answer

Challenge 3

Read a member as a binary stream, then decode its UTF-8 content.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory
import tarfile

with TemporaryDirectory() as folder:
    root = Path(folder)
    source = root / "hello.txt"
    source.write_text("Hello", encoding="utf-8")
    archive_path = root / "hello.tar"
    with tarfile.open(archive_path, "w") as archive:
        archive.add(source, arcname="hello.txt")
    with tarfile.open(archive_path) as archive:
        with archive.extractfile("hello.txt") as stream:
            message = 
    assert message == "Hello"
    print(message)

Press Ctrl⌘Enter to check your answer

Challenge 4

Extract the known member to the temporary destination using the standard data filter.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory
import tarfile

with TemporaryDirectory() as folder:
    root = Path(folder)
    source = root / "hello.txt"
    source.write_text("Hello", encoding="utf-8")
    archive_path = root / "hello.tar"
    with tarfile.open(archive_path, "w") as archive:
        archive.add(source, arcname="hello.txt")
    destination = root / "out"
    destination.mkdir()
    with tarfile.open(archive_path) as archive:
        
    assert (destination / "hello.txt").read_text(encoding="utf-8") == "Hello"
    print("controlled extraction complete")

Press Ctrl⌘Enter to check your answer