How to search and replace text in a file?

前端 未结 15 2198
傲寒
傲寒 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:10

    Like so:

    def find_and_replace(file, word, replacement):
      with open(file, 'r+') as f:
        text = f.read()
        f.write(text.replace(word, replacement))
    

提交回复
热议问题