How to search and replace text in a file?

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

    fileinput already supports inplace editing. It redirects stdout to the file in this case:

    #!/usr/bin/env python3
    import fileinput
    
    with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(text_to_search, replacement_text), end='')
    

提交回复
热议问题