RReplacent
Workflows

Coding workflows · Atomic UTF-8 file replacement

03
Built around your work

A concrete starting point

Replace a UTF-8 file through a temporary file in the same directory. Test empty text, Unicode and replacement failure, closing the temporary handle before replacement and removing leftovers while preserving the old file on that failure.

01

Open the context

Choose the project folder and name the files or behavior involved.

02

Define the change

Describe the input, expected output and boundaries that must stay intact.

03

Inspect the work

Review the proposed edits and any commands before relying on their result.

04

Check the outcome

Compare actual behavior with the expected result. If a check fails, investigate it before applying more changes.

Atomic UTF-8 file replacement

A concrete starting point
import os
from pathlib import Path
from tempfile import NamedTemporaryFile

def replace_utf8(path, text):
    if not isinstance(path, (str, Path)) or type(text) is not str:
        raise ValueError("replace.input")
    target, data = Path(path), text.encode("utf-8")
    temporary = None
    try:
        with NamedTemporaryFile(dir=target.parent, prefix=".swap-", delete=False) as out:
            temporary = Path(out.name)
            out.write(data)
        os.replace(temporary, target)
    finally:
        if temporary is not None:
            temporary.unlink(missing_ok=True)

The example is a starting point for a real project, not a claim that generated code is already tested. Adjust paths, dependencies and expected behavior to match your application.

AI coding workspace

Your next change starts here.

Get the Windows app ↗