Sometimes, we want to search and replace text in a file with Python.
In this article, we’ll look at how to search and replace text in a file with Python.
How to search and replace text in a file with Python?
To search and replace text in a file with Python, we can use the string replace method.
For instance, we write
with open('file.txt', 'r') as file :
file_data = file.read()
file_data = file_data.replace('ram', 'abcd')
with open('file.txt', 'w') as file:
file.write(file_data)
to open the file.txt file with open.
Then we call file_data.replace with the text we want to replace and the text replacement strings.
Then we call open to open the file again with 'w' to get write permission to the file.
And then we call file.write with file_data to overwrite the existing contents.
Conclusion
To search and replace text in a file with Python, we can use the string replace method.