How do you search for a specific string across multiple text files in Python? | A1Lab@MZeeshanM to PythonEnglish •
edit-2
2 days ago

How do you search for a specific string across multiple text files in Python?

message-square
0

Combine Path(root_dir).rglob("*.txt") from pathlib with streaming line-by-line iteration (with path.open("r", encoding="utf-8", errors="ignore") as f:) and substring containment (if needle in line:) or compiled regex (pattern.search(line)) so files of any size are scanned in $O(1)$ memory per file without loading entire multi-gigabyte files into RAM.

Basic Example

import re
from pathlib import Path

def search_files(
    root_dir: str | Path,
    query: str,
    glob_pattern: str = "*.txt",
    case_sensitive: bool = True,
) -> list[tuple[Path, int, str]]:
    matches: list[tuple[Path, int, str]] = []
    target = query if case_sensitive else query.casefold()

    # 1. Recommended: Stream line-by-line across recursively matched files
    for path in sorted(Path(root_dir).rglob(glob_pattern)):
        if not path.is_file():
            continue
        with path.open("r", encoding="utf-8", errors="ignore") as f:
            for line_no, line in enumerate(f, start=1):
                haystack = line if case_sensitive else line.casefold()
                if target in haystack:
                    matches.append((path, line_no, line.rstrip("\r\n")))
    return matches

# Example usage:
for file_path, line_num, text in search_files("logs", "ERROR", glob_pattern="*.log"):
    print(f"{file_path}:{line_num}: {text}")

# 2. Regex search across multiple files (whole words, wildcards, or multi-pattern):
PATTERN = re.compile(r"\bERR-\d{4}\b")
for path in Path("logs").rglob("*.log"):
    if path.is_file():
        with path.open("r", encoding="utf-8", errors="ignore") as f:
            for line_no, line in enumerate(f, start=1):
                if PATTERN.search(line):
                    print(f"{path}:{line_no}: {line.rstrip()}")

Key Details & Edge Cases

  • Why streaming line-by-line beats path.read_text() on large files:
    • Calling if query in path.read_text(): reads the entire file into memory as a single string and gives no line number. Iterating for line_no, line in enumerate(f, start=1): uses a fixed buffer ($O(1)$ memory), reports exact 1-based line numbers, and lets you break early if you only need to know whether a file contains the string.
  • Avoid UnicodeDecodeError when scanning mixed or unknown files (errors="ignore" / binary check):
    • A single non-UTF-8 byte or binary file matching * will crash a loop unless you pass errors="ignore" (or errors="replace") to .open(). To skip binary files completely before reading, check the first 8 KB for null bytes (b"\x00" in chunk).
  • Skipping heavy directories (.git, node_modules, .venv) during traversal:
    • Path.rglob() enters every subdirectory before yielding paths. When searching large project trees, use os.walk() and mutate dirs[:] = [d for d in dirs if d not in {".git", ".venv", "node_modules", "__pycache__"}] in-place to prune ignored folders before scanning their files.
  • Multi-line patterns spanning across \n line breaks:
    • Line-by-line iteration will miss matches that cross newline boundaries (e.g., "BEGIN\n...END"). For multi-line regexes on reasonably sized text files, read the file content (text = path.read_text(encoding="utf-8", errors="ignore"))