Python Code to Search and Replace a String in a Text File

AuthorSumit Dey Sarkar

Pubish Date30 Apr 2023

categoryPython

In this tutorial we will learn Python code to search and replace a string in a text file.

 

Python Code to Search and Replace a String in a Text File

 

Python code to search and replace a string in a text file

Using Python, you can use the built-in re module, which offers regular expression matching operations, to search and replace a string in a text file.

 

Here's an example code:

import re

# define the search and replace strings
search_str = 'old_string'
replace_str = 'new_string'

# read the input file
with open('input.txt', 'r') as file:
    filedata = file.read()

# perform the search and replace operation using re.sub()
newdata = re.sub(search_str, replace_str, filedata)

# write the modified data to the output file
with open('output.txt', 'w') as file:
    file.write(newdata)

In this example, the re.sub() method is used to replace all occurrences of the search_str with replace_str in the filedata. The modified data is then written to a new file named output.txt.

 

You can modify the search_str and replace_str variables according to your needs. You need confirm that the input file input.txt is present in the current working directory.

 

Comments 0

Leave a comment