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.
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:
Use replace() method in Python to search and replace text 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'
try:
# 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)
except FileNotFoundError:
print(f"Error: The file '{filepath}' was not found.")
except PermissionError:
print(f"Error: Permission denied when accessing '{filepath}'.")
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
Alternatively, you can use the re module to perform regular expression search and replace:
Use re module for regex search & replace in Python
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)Note:
re.sub()treats the pattern as a regular expression. If your search string contains special regex characters (like.,*,?), wrap it inre.escape(pattern)to treat it as a literal string.
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 use shutil.copy():
Use shutil.copy() to create a file backup
import shutil
shutil.copy(filepath, filepath + '.bak')Note: These methods are designed for text files. For binary files, open the file in
'rb'and'wb'modes and handle bytes accordingly.