-2

I have a file and I want to change a particular string in the file. Here is what I am trying

import re
with open ('input.txt', 'rw' ) as f:
    content = f.read()
    content_new = re.sub('destination', r'TEST', content, flags = re.M)

But this is not actually doing anything or updating the file. i.e I am not seeing the destination updated to TEST . Can someone help me and tell me what I am doing wrong?

Is it that I am not writing to file? or ??

Thân LƯƠNG Đình
  • 3,082
  • 2
  • 11
  • 21

1 Answers1

1

You are not saving your modification. You have read the contents of your file and modified it - But then you are throwing away the modification.

Here's a simple example of you can write it to a different file called output

import re
with open ('input.txt', 'rw' ) as f:
    content = f.read()
    print(content) # Original content

    content_new = re.sub('destination', r'TEST', content, flags = re.M)
    print(content_new) # Modified content

    f2 = open('output.txt', 'w') # Writing to a different file
    f2.write(content_new)
    f2.close()

Also, read the answers to this question - How to modify a text file?

Nikhil Baliga
  • 137
  • 1
  • 1
  • 8
  • I see, But i wanna write to same file – KsitiMisti shisty Oct 08 '20 at 14:23
  • Yes - That's why I provided a link at the bottom. There are certain associated challenges well explained there – Nikhil Baliga Oct 08 '20 at 14:24
  • @KsitiMistishisty To keep the data safe, you need a separate output file. If everything (edit, write, close - see also fsync) has finished without errors, only then is it OK to replace the original file by the output file. Should anything unexpected happen, just remove the output file and start over. – VPfB Oct 08 '20 at 14:35