Batch Find and Replace in Text Files with Python

Handling multiple text files and performing find-and-replace operations can be a daunting task, especially when done manually. Python simplifies this process, allowing batch processing of text files with minimal effort. This article examines a Python script designed to search and replace text across multiple .txt files within a specified folder.

Python Script for Batch Find and Replace

Script Overview

The purpose of this script is to automate the find-and-replace process across multiple text files. This is particularly useful for tasks like updating information, correcting errors, or altering data in a batch of documents.

Importing the os Module

import os

The script starts by importing the os module, which is vital for interacting with the operating system and handling file paths.

Setting Up Folder and Strings

folder_path = '/txt/'  # Replace with your folder path
search_str = 'text to find'
replace_str = 'text to be replaced'
  • folder_path: The directory where the text files are located.
  • search_str: The string to search for in the files.
  • replace_str: The string that will replace the search_str.

Iterating Over Text Files

for filename in os.listdir(folder_path):
    if filename.endswith('.txt'):
        file_path = os.path.join(folder_path, filename)
        # File processing continues here

The script loops through each file in the specified directory, focusing only on .txt files.

Reading and Modifying the File Content

with open(file_path, 'r', encoding='utf-8') as f:
    content = f.read()

new_content = content.replace(search_str, replace_str)

Each file’s content is read, and the replace method is used to substitute search_str with replace_str.

Writing the Modified Content Back to the File

if content != new_content:
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(new_content)
    print(f"Modified {filename}")

The script checks if any changes have been made and, if so, writes the modified content back to the file.

Handling Exceptions

except Exception as e:
    print(f"Error processing {filename}: {e}")

The script includes error handling to catch and report any issues during file processing.

Conclusion

This Python script demonstrates a practical solution for performing find-and-replace operations across multiple text files. It offers a significant time-saving advantage for batch editing tasks, eliminating the tedium of manual text manipulation. Python’s ease of use and robust file handling capabilities make it an excellent choice for automating such file management tasks, enhancing efficiency and accuracy.