How to search and replace text in a file?

There are several ways to search and replace text in a file, depending on the programming language you are using. Here is a Python code snippet that uses the replace() method to replace all occurrences of a specified string in a file:

import os

# specify the filepath and the strings to be searched and replaced
filepath = 'path/to/file.txt'
old_string = 'old_text'
new_string = 'new_text'

# open the file and read its contents
with open(filepath, 'r') as file:
    filedata = file.read()

# replace the old string with the new string
filedata = filedata.replace(old_string, new_string)

# write the modified data back to the file
with open(filepath, 'w') as file:
    file.write(filedata)

Watch a course Python - The Practical Guide

Alternatively, you can use the re module to perform regular expression search and replace:

import re

# specify the filepath and the strings to be searched and replaced
filepath = 'path/to/file.txt'
pattern = 'old_text'
replacement = 'new_text'

# open the file and read its contents
with open(filepath, 'r') as file:
    filedata = file.read()

# perform the search-and-replace
filedata = re.sub(pattern, replacement, filedata)

# write the modified data back to the file
with open(filepath, 'w') as file:
    file.write(filedata)

Please note that this code snippet will overwrite the original file with the new text. If you want to make a backup of the original file before making any changes, you can add a line before the with open(filepath, 'w') block

os.rename(filepath,filepath+'.bak')