To replace text in a file with Python, read the content, use str.replace() or re.sub(), and write the result back. For small files, reading the whole file is fine. For large files, stream line by line into a temporary file, then replace the original.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
Quick answer: replace string in a file
For a small file, read it, replace the text, and write back:
from pathlib import Path
path = Path("config.txt")
text = path.read_text(encoding="utf-8")
path.write_text(text.replace("input", "output"), encoding="utf-8")For a large file, write replaced lines to a temporary file, then swap it into place. Use fileinput only when you specifically want in-place filtering with backup.
Python replace string in file quick reference
| Task | Use |
|---|---|
| Replace in same small file | Path.read_text() → replace() → Path.write_text() |
| Replace and save to new file | Read source, write replaced lines to new path |
| Replace line by line | for line in file: out.write(line.replace(old, new)) |
| Large file safely | Stream to .tmp, then tmp.replace(original) |
| In-place with backup | fileinput.FileInput(..., inplace=True, backup=".bak") |
| Pattern-based replace | re.sub(pattern, repl, text) |
| Count replacements | text.count(old) before/after or regex logic |
Replace text and write to a new file
Keep the original file unchanged and save the result elsewhere. This is the safest first approach when you want a backup copy automatically.
from pathlib import Path
source = Path("a.txt")
target = Path("b.txt")
text = source.read_text(encoding="utf-8")
target.write_text(text.replace("input", "output"), encoding="utf-8")Line-by-line streaming also works when files are large:
from pathlib import Path
source = Path("a.txt")
target = Path("b.txt")
with source.open(encoding="utf-8") as src, target.open("w", encoding="utf-8") as dst:
for line in src:
dst.write(line.replace("input", "output"))Sample a.txt:
line 1
line 2
this is an input file
line 4After the script runs, b.txt contains output instead of input. See Python write to file for more file-writing patterns.
Replace text in the same file (small files)
For small files, read the entire content, replace the string, and overwrite the file.
from pathlib import Path
path = Path("a.txt")
text = path.read_text(encoding="utf-8")
path.write_text(text.replace("input", "output"), encoding="utf-8")Path.read_text() returns the file contents as a string. Path.write_text() writes text back and overwrites an existing file with the same name. For extracting or checking substrings before you replace them, see Python substring.
This pattern is simple and readable. Avoid it when the file is too large to load into memory at once, or when an interrupted write could leave the file half-written without a backup.
Replace text in large files safely
Stream input line by line into a temporary file, then replace the original only after the write succeeds.
from pathlib import Path
path = Path("big.log")
temp = path.with_suffix(path.suffix + ".tmp")
with path.open(encoding="utf-8") as src, temp.open("w", encoding="utf-8") as dst:
for line in src:
dst.write(line.replace("ERROR", "WARN"))
temp.replace(path)Path.replace() moves the temporary file over the original path. If the script fails before that step, the original file stays untouched.
Replace text in place with fileinput
Use fileinput when you want in-place line editing with an optional backup extension.
from pathlib import Path
import fileinput
path = Path("input.txt")
with fileinput.FileInput(path, inplace=True, backup=".bak", encoding="utf-8") as f:
for line in f:
print(line.replace("input", "output"), end="")With backup=".bak", Python creates input.txt.bak before rewriting input.txt. Use print(..., end="") because fileinput already gives you each line including its newline.
Do not mix fileinput with a separate open(..., "r+") on the same file. Let fileinput handle in-place replacement.
Replace text using regex
Use re.sub() when the match is a pattern, not a fixed literal string. See Python regex for more pattern-matching techniques.
from pathlib import Path
import re
path = Path("boot.cfg")
text = path.read_text(encoding="utf-8")
updated = re.sub(r"initrd\.img", "patch.img", text)
path.write_text(updated, encoding="utf-8")For line-based regex work on large files, apply re.sub() inside the streaming loop instead of loading the whole file.
Which method should you use?
| Situation | Recommended approach |
|---|---|
| Small file, same path | read_text() → replace() → write_text() |
| Keep original, write new file | Read source, write to new path |
| Very large file | Stream to temp file, then replace original |
| In-place edit with backup | fileinput.FileInput(..., inplace=True, backup=".bak") |
| Pattern match | re.sub() |
| Simple literal swap | str.replace() |
Summary
Replace text in a Python file by reading content, applying str.replace() or re.sub(), and writing the result back. For small files, Path.read_text() and Path.write_text() are enough. For large files, stream to a temporary file and swap it into place. Use fileinput when you want in-place filtering with backup. For checking whether text exists before replacing, see check if string contains substring.
References
- Python
pathlib.Path.read_text() - Python
pathlib.Path.write_text() - Python
fileinputmodule - Python
re.sub()documentation - Python
str.replace()documentation

