How to search and replace text in a file?

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

    With a single with block, you can search and replace your text:

    with open('file.txt','r+') as f:
        filedata = f.read()
        filedata = filedata.replace('abc','xyz')
        f.truncate(0)
        f.write(filedata)
    

提交回复
热议问题