How to replace in a .txt file?

Can we change a particular word in text file with replace(), after opening the file with open() and then print the desired result in output?

I tried this, ouput was not what i expected. Kindly correct if something is missing :

fhandle=open(‘mbox.txt’)
for q in fhandle:
if q.startswith(‘3rd’):
q.replace(‘3rd’,‘This’)
print(q)

OUTPUT:
This is a line.

This is another line.

3rd line is an exception.

This is the fourth line.

I was trying to replace ‘3rd’ with ‘This’.

THANKS.

You are opening the file in read mode.
When you replace it will not be modify the original content of the file.
Open the file in write “w” mode, then replace the content. that you want to write.

All the best!

1 Like

Yeah. Did it in the exercise :+1:
Thanks for the reply! :slightly_smiling_face: