Batu Lab NotesPractical developer guides

Write a UTF-8 manifest into a temporary folder

By Batu · English technical notes

Also published in our Blogger archive.

Write a UTF-8 manifest into a temporary folder

A manifest needs a defined representation when other tools will read it. This example creates an isolated directory with TemporaryDirectory, constructs a small JSON value containing café, and writes manifest.json through Path.write_text. Passing encoding="utf-8" makes the file encoding explicit. json.dumps(..., ensure_ascii=False) retains the accented character in the text rather than emitting a JSON Unicode escape, while the appended newline makes the complete file content deliberate.

The byte assertion checks the actual UTF-8 encoding of the controlled document, including é as two bytes and the final newline. The other assertion checks the return value from write_text, which is the number of characters written; that is intentionally different from the byte length for this content. The program prints counts and the document, rather than its temporary path, so stdout is deterministic.

TemporaryDirectory is available from Python 3.2, and Path.write_text from Python 3.5. The temporary directory is cleaned up when the context exits. write_text opens, writes, and closes its target, and it replaces existing content; it is neither an append API nor concurrency control. These assertions verify this fixture only, not durability after a crash or safe coordination with another writer. See the TemporaryDirectory documentation and Path.write_text reference.

AI-assistance disclosure: AI helped draft this educational article.

from pathlib import Path
from tempfile import TemporaryDirectory
import json

with TemporaryDirectory() as directory:
    manifest_path = Path(directory) / "manifest.json"
    manifest = {"name": "café", "version": 1}
    text = json.dumps(manifest, ensure_ascii=False, separators=(",", ":")) + "\n"

    written = manifest_path.write_text(text, encoding="utf-8")
    raw = manifest_path.read_bytes()

    assert raw == b'{"name":"caf\xc3\xa9","version":1}\n'
    assert written == len(text)

    print(f"characters={written}; bytes={len(raw)}")
    print(manifest_path.read_text(encoding="utf-8"), end="")
characters=28; bytes=29
{"name":"café","version":1}