How to search and replace text in a file in Python
Published on Aug. 22, 2023, 12:15 p.m.
To search and replace text in a file in Python, you can use the built-in open()
function to open the file in “read” mode, read the contents of the file, replace the desired text, and then write the modified contents back to the file. Here’s an example:
with open('myfile.txt', 'r') as f:
file_contents = f.read()
file_contents = file_contents.replace('old text', 'new text')
with open('myfile.txt', 'w') as f:
f.write(file_contents)
In this example, we use the with
statement and the open()
function to open the file 'myfile.txt'
in “read” mode, and read its contents into the variable file_contents
. Then, we replace the text “old text” with “new text” in file_contents
using the replace()
function. Finally, we use open()
with the mode “write” to open the file again and overwrite its contents with the modified contents in file_contents
.
Note that this method replaces all occurrences of the specified text in the file. If you want to replace only a single occurrence, you can use regular expressions to search for the text and replace only the first match. Here’s an example:
import re
with open('myfile.txt', 'r') as f:
file_contents = f.read()
new_contents, num_replacements = re.subn('old text', 'new text', file_contents, count=1)
with open('myfile.txt', 'w') as f:
f.write(new_contents)
In this example, we use the re.subn()
function to replace the first occurrence of “old text” with “new text” in file_contents
. The modified contents are returned in the new_contents
variable, along with the number of replacements made in num_replacements
.