How to search and replace text in a file?

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

    You can also use pathlib.

    from pathlib2 import Path
    path = Path(file_to_search)
    text = path.read_text()
    text = text.replace(text_to_search, replacement_text)
    path.write_text(text)
    

提交回复
热议问题