# Read in the file with open('file.txt', 'r') as file : filedata = file.read() # Replace the target string filedata = filedata.replace('ram', 'abcd') # Write the file out again with open('file.txt', 'w') as file: file.write(filedata)
Here is what the above code is Doing:
1. Opening the file in read mode and storing the contents in filedata.
2. Replacing all occurrences of the required string in filedata.
3. Opening the file again in write mode and writing the resulting data in it.