How to find and replace text in multiple files in Python
How to find and replace text in multiple files in Python.
Here's a detailed step-by-step tutorial on how to find and replace text in multiple files using Python.
Step 1: Import Required Modules
First, you need to import the necessary modules in your Python script. In this case, we will use the os module for file operations and the fileinput module for in-place file editing.
import os
import fileinput
Step 2: Define the Find and Replace Function
Next, let's define a function to perform the find and replace operation. This function will take three parameters: the directory path where the files are located, the search string to find, and the replacement string.
def find_replace(directory, search, replace):
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
with fileinput.FileInput(filepath, inplace=True) as file:
for line in file:
print(line.replace(search, replace), end='')
Step 3: Call the Find and Replace Function
Now, you can call the find_replace function with the appropriate parameters. For example, if you want to find and replace the text "old" with "new" in all files within a directory called "files", you can do the following:
find_replace("files", "old", "new")
Step 4: Run the Script
Save the Python script with a .py extension (e.g., find_replace.py) and run it using a Python interpreter. The script will recursively search for the specified search string in all files within the given directory and replace it with the specified replacement string.
Example Usage
Let's say we have a directory named "files" with two text files file1.txt and file2.txt. Both files contain the word "old", and we want to replace it with "new".
file1.txt:
This is an old file.
file2.txt:
This is another old file.
After running the script with the following command:
python find_replace.py
The contents of file1.txt and file2.txt will be updated as follows:
file1.txt:
This is an new file.
file2.txt:
This is another new file.
That's it! You have successfully found and replaced text in multiple files using Python.
Please note that this script performs an in-place replacement, meaning it modifies the original files. If you want to keep the original files intact and create new files with the replaced text, you need to modify the script accordingly.