Read the file’s contents with Path.read_text(encoding="utf-8"), perform the replacement with str.replace(old, new) (or re.sub(pattern, repl, text) for regular expressions), and write the updated string back via Path.write_text(updated, encoding="utf-8") for files that fit comfortably in memory—or stream line-by-line into a tempfile.NamedTemporaryFile in the same directory and atomically swap it into place with os.replace(tmp_path, target_path) for large files or crash-safe in-place updates.
Basic Example
from pathlib import Path
import re
file_path = Path("config.ini")
# 1. Recommended for standard-sized files (< 100 MB): Read -> Replace -> Write
text = file_path.read_text(encoding="utf-8")
updated = text.replace("DEBUG = False", "DEBUG = True")
file_path.write_text(updated, encoding="utf-8")
# 2. Regex search-and-replace across the entire file:
updated_regex = re.sub(r"port\s*=\s*\d+", "port = 8080", updated)
file_path.write_text(updated_regex, encoding="utf-8")
Key Details & Edge Cases
- Crash-safe streaming replacement for large files (
tempfile+os.replace):- Calling
file_path.write_text(...)directly truncates the target file before writing; if the script crashes or loses power mid-write, the original file is destroyed. For large files (gigabytes) or critical configuration files, stream line-by-line into a temporary file created indir=file_path.parent(same filesystem soos.replaceis atomic) and replace the original only after closing:import os from pathlib import Path import tempfile target = Path("server.log") with ( target.open("r", encoding="utf-8") as src, tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", dir=target.parent, delete=False ) as tmp, ): tmp_path = Path(tmp.name) for line in src: tmp.write(line.replace("WARN", "WARNING")) os.replace(tmp_path, target) # Atomic rename on POSIX & Windows
- Calling
- Avoid
open(path, "r+")for variable-length replacements:- Opening a file in
"r+"mode overwrites bytes in place without shifting subsequent characters. If"old"(3 bytes) is replaced with"newer"(5 bytes),"r+"corrupts the following 2 bytes of the file, and if replaced with"hi"(2 bytes), trailing leftover characters remain at the end unless you manuallyf.truncate().
- Opening a file in
- Preserve original line endings on Windows (
newline=""):Path.read_text()translates\r\nto\nandPath.write_text()writes OS-native line endings (\r\non Windows). To keep exact existing line endings untouched when editing cross-platform files, open withopen(path, "r", encoding="utf-8", newline="")andopen(path, "w", encoding="utf-8", newline="").
- Optional
fileinput.input(..., inplace=True, backup=".bak"):- Python’s built-in
fileinputmodule can redirectprint()statements back into the source file (with fileinput.input("app.conf", inplace=True, backup=".bak") as f: for line in f: print(line.replace("foo", "bar"), end="")), thoughtempfile+os.replaceis preferred in production becausefileinputhijacks globalsys.stdout.
- Python’s built-in
- Skip rewriting the file when no match was found (
if updated != text:):- Guarding
file_path.write_text(updated, encoding="utf-8")behindif updated != text:avoids modifying the file’smtimetimestamp or triggering file watchers / build systems unnecessarily when zero replacements occurred.
- Guarding
Comparison of In-Place File Search-and-Replace Approaches in Python
| Approach | Memory Usage | Crash-Safe / Atomic? | Supports Multi-Line Matches? | Best Used When |
|---|---|---|---|---|
Path.read_text() + .replace() / re.sub() + Path.write_text() (Recommended) |
$O(\text{file size})$ | No (truncates directly on write) | Yes (whole file is in memory) | Small-to-medium config files, source code, or scripts under ~100 MB. |
Line-by-line tempfile.NamedTemporaryFile + os.replace() (Recommended for large/critical files) |
$O(1)$ streaming | Yes (atomic rename on completion) | No (operates one line at a time) | Multi-gigabyte log files, production configs, or datasets where partial writes are unacceptable. |
fileinput.input(path, inplace=True, backup=".bak") |
$O(1)$ streaming | Partial (creates .bak backup first) |
No (line-by-line via redirected print) |
Quick one-off CLI scripts where automatic .bak backup files are desired. |
open(path, "r+") + seek(0) + truncate() |
$O(\text{file size})$ | No (corrupts file if interrupted mid-write) | Yes | Not recommended—prone to trailing-byte bugs if f.truncate() is omitted. |
You must log in or register to comment.
