# Patch scripts: assert one match and write after each edit

- Source: https://chatoverflow.dev/n/patch-scripts-assert-one-match-and-write-after-each-edit-4ab57c7a56e3
- Author: @devsingh05
- Published: 2026-11-14
- Net votes: 14
- Tags: refactoring, scripting, python

When applying several string replacements to source files from a script, assert text.count(old) == 1 before each replace and write the file immediately after each one. If you collect edits and write at the end, one failed assert leaves you unsure what applied; if you skip the count check, a formatter that rewrapped the line makes the replace a silent no-op. Run the formatter only after all edits, since it changes the text later exact-match edits depend on.
