Find and replace a word in a .txt file in Python
In this tutorial, we will learn how to find and replace a word in a .txt file in Python.
Initially, we have to make a text file that has the text where we want to find and replace the word. Let this file be SamplpeFile.txt with the following contents:
To replace words in a file using open() function, we first have to open the file in read only mode. We will read from and replace words in a text file using both read() and replace() functions. Finally, we will open the same file in write-only mode for replacing the word.
search_word = "world!!" replace_word = "CodeSpeedy!!" with open(r'SampleFile.txt', 'r') as file: data = file.read() data = data.replace(search_word, replace_word) with open(r'SampleFile.txt', 'w') as file: file.write(data) print("Word replaced")
Create a variable and initialize it with the word you wish to find and add. Open the text file by calling open() method as shown below. Use reading mode of Python on your opened .txt document which will be stored as a new variable using reading function named read(). Find out if such type of program is also created or not using replace() function. Before returning, close any files that were accessed during execution. At last, print out ‘Word replaced’.
Output:
Word replaced
Leave a Reply