How to search and replace text in a file?

前端 未结 15 2200
傲寒
傲寒 2020-11-21 20:29

How do I search and replace text in a file using Python 3?

Here is my code:

import os
import sys
import fileinput

print (\"Text to search for:\")
te         


        
15条回答
  •  梦如初夏
    2020-11-21 21:08

    Late answer, but this is what I use to find and replace inside a text file:

    with open("test.txt") as r:
      text = r.read().replace("THIS", "THAT")
    with open("test.txt", "w") as w:
      w.write(text)
    

    DEMO

提交回复
热议问题