How do you search and replace text directly inside a file using Python? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you search and replace text directly inside a file using Python?

message-square
0

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 in dir=file_path.parent (same filesystem so os.replace is 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
      
  • 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 manually f.truncate().
  • Preserve original line endings on Windows (newline=""):
    • Path.read_text() translates \r\n to \n and Path.write_text() writes OS-native line endings (\r\n on Windows). To keep exact existing line endings untouched when editing cross-platform files, open with open(path, "r", encoding="utf-8", newline="") and open(path, "w", encoding="utf-8", newline="").
  • Optional fileinput.input(..., inplace=True, backup=".bak"):
    • Python’s built-in fileinput module can redirect print() 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="")), though tempfile + os.replace is preferred in production because fileinput hijacks global sys.stdout.
  • Skip rewriting the file when no match was found (if updated != text:):
    • Guarding file_path.write_text(updated, encoding="utf-8") behind if updated != text: avoids modifying the file’s mtime timestamp or triggering file watchers / build systems unnecessarily when zero replacements occurred.

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.