python how to replace a certain string in text

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

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:

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 filedata back into it.