Search and replace a line in a file in Python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Replacing a line in a file sounds simple, but the right implementation depends on whether you want to match exact lines, replace only the first match, or preserve the file safely if something fails mid-write. In Python, the safest general pattern is to write a new file and replace the original only after the rewrite succeeds.
The Safe Rewrite Pattern
Most text files are small enough to process line by line into a temporary file. That gives you a clean failure boundary.
This rewrites the file safely and then atomically swaps the temporary file into place.
Replace Only the First Matching Line
Sometimes you want only one replacement, not every identical line.
That keeps the change narrowly scoped when repeated identical lines exist in the file.
Match by Pattern Instead of Exact Equality
If the target line contains variable content, a regex or prefix match is more useful than exact comparison.
This is a better fit for config-style files where the value changes but the key identifies the line.
Be Careful With Newlines and Encoding
Line replacement bugs often come from newline handling, not from the replacement logic itself. If you strip line endings and forget to restore them, the rewritten file may end up with merged lines or inconsistent formatting.
Encoding matters too. If the file is not UTF-8, open it with the correct encoding or you may corrupt the contents during rewrite.
When fileinput Is Good Enough
Python’s fileinput module supports in-place editing and is convenient for quick scripts.
This is fine for lightweight automation, but the explicit temporary-file approach is easier to control in production code.
Preserve File Semantics, Not Just Text
Some files carry meaning in line order, trailing newlines, or comment formatting. A replacement script that changes those incidentally can still break the consuming tool even though the target line was updated correctly.
That is why line replacement should be treated as a file-editing operation, not just a string substitution exercise.
Common Pitfalls
The biggest mistake is reading and writing the same file handle at once without a safe rewrite strategy.
Another issue is forgetting whether you want to replace all matches or only the first one.
A third problem is mishandling newlines and encoding, which can corrupt the file even when the line-matching logic is correct.
Summary
- The safest general approach is rewrite-to-temp and then replace the original file.
- Decide whether you need exact line matching, pattern matching, or first-match-only behavior.
- Preserve newline style and file encoding intentionally.
- Use
fileinputfor quick scripts, but prefer explicit file replacement for robust tooling. - Treat file rewriting as a data-integrity task, not just a string operation.

