How to search and replace text in a file?

前端 未结 15 2201
傲寒
傲寒 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='')
    
    0 讨论(0)
  • 2020-11-21 21:30

    (pip install python-util)

    from pyutil import filereplace
    
    filereplace("somefile.txt","abcd","ram")
    

    The second parameter (the thing to be replaced, e.g. "abcd" can also be a regex)
    Will replace all occurences

    0 讨论(0)
  • 2020-11-21 21:31
    def word_replace(filename,old,new):
        c=0
        with open(filename,'r+',encoding ='utf-8') as f:
            a=f.read()
            b=a.split()
            for i in range(0,len(b)):
                if b[i]==old:
                    c=c+1
            old=old.center(len(old)+2)
            new=new.center(len(new)+2)
            d=a.replace(old,new,c)
            f.truncate(0)
            f.seek(0)
            f.write(d)
        print('All words have been replaced!!!')
    
    0 讨论(0)
提交回复
热议问题