How to search and replace text in a file?

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

    You can do the replacement like this

    f1 = open('file1.txt', 'r')
    f2 = open('file2.txt', 'w')
    for line in f1:
        f2.write(line.replace('old_text', 'new_text'))
    f1.close()
    f2.close()
    

提交回复
热议问题