1
with open ('npt.mdp','r+') as npt:
    if 'Water_and_ions' in npt.read():
        print(" I am replacing water and Ions...with only Water")
        s=npt.read()
        s= s.replace('Protein_BSS Water_and_ions', 'Protein_BSS Water')
        with open ('npt.mdp',"w") as f:
            f.write(s)

Text I want to replace is not being replaced. Why?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Ron Ledger
  • 35
  • 7

1 Answers1

0

There is a dupe for what you want to do: How to search and replace text in a file using Python?

Here is why your approach did not work:

You consume your filestream by checking if 'Water_and_ions' in npt.read(): - afterwards the s=npt.read() can not read anything anymore because the stream is at its end.

Fix:

with open ('npt.mdp','r+') as npt:
    s = npt.read()                       # read here
    if 'Water_and_ions' in s:            # test s
        print(" I am replacing water and Ions...with only Water")

        s = s.replace('Protein_BSS Water_and_ions', 'Protein_BSS Water')
        with open ('npt.mdp',"w") as f:
            f.write(s)

Instead of reading the file into a variable you could also seek(0) back to the files start - but if you want to modify it anyway, the options in the dupe are better suited to work for archieving your goal.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69