How to search and replace text in a file?

前端 未结 15 2199
傲寒
傲寒 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

    I modified Jayram Singh's post slightly in order to replace every instance of a '!' character to a number which I wanted to increment with each instance. Thought it might be helpful to someone who wanted to modify a character that occurred more than once per line and wanted to iterate. Hope that helps someone. PS- I'm very new at coding so apologies if my post is inappropriate in any way, but this worked for me.

    f1 = open('file1.txt', 'r')
    f2 = open('file2.txt', 'w')
    n = 1  
    
    # if word=='!'replace w/ [n] & increment n; else append same word to     
    # file2
    
    for line in f1:
        for word in line:
            if word == '!':
                f2.write(word.replace('!', f'[{n}]'))
                n += 1
            else:
                f2.write(word)
    f1.close()
    f2.close()
    

提交回复
热议问题