Skip to content
Foxipa
Code Completion 4 Challenges

Complete the temporary-file code

Practise temporary workspaces, file positioning, named-file cleanup, and spooled-storage rollover.

Intermediate ~10 min read

Challenge 1

Use the TemporaryDirectory workspace to print the temporary file name after writing it.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    report = Path(directory) / "report.txt"
    report.write_text("ready", encoding="utf-8")
    
    assert report.read_text(encoding="utf-8") == "ready"
print(Path(directory).exists())

Press Ctrl⌘Enter to check your answer

Challenge 2

Move the file position back to the beginning before reading the scratch text.

python Your answer
from tempfile import TemporaryFile

with TemporaryFile(mode="w+t", encoding="utf-8") as scratch:
    scratch.write("summary")
    
    print(scratch.read())

Press Ctrl⌘Enter to check your answer

Challenge 3

Set the named temporary file not to delete itself on close, because the following code reopens the path. The exercise also removes the path in finally.

python Your answer
from pathlib import Path
from tempfile import NamedTemporaryFile

path = None
try:
    with NamedTemporaryFile(mode="w", encoding="utf-8", ) as temporary:
        path = Path(temporary.name)
        temporary.write("read me")
    print(path.read_text(encoding="utf-8"))
finally:
    if path is not None:
        path.unlink(missing_ok=True)

Press Ctrl⌘Enter to check your answer

Challenge 4

Force the spooled file to switch to disk-backed storage before reading its contents.

python Your answer
from tempfile import SpooledTemporaryFile

with SpooledTemporaryFile(max_size=64, mode="w+t", encoding="utf-8") as scratch:
    scratch.write("some data")
    scratch.
    scratch.seek(0)
    print(scratch.read())

Press Ctrl⌘Enter to check your answer