Open the context
Choose the project folder and name the files or behavior involved.
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.
Choose the project folder and name the files or behavior involved.
Describe the input, expected output and boundaries that must stay intact.
Review the proposed edits and any commands before relying on their result.
Compare actual behavior with the expected result. If a check fails, investigate it before applying more changes.
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.