Logo TheBeArsenal

Python | Technical Handbook

Search and Replace a word in the file using Python

Solution
# Read and save file content
with open('file.txt', 'r') as file :
filedata = file.read()
# Replace words with new ones.
filedata = filedata.replace('abc', 'def')
# Overwrite the file with new contents
with open('file.txt', 'w') as file:
file.write(filedata)