Search and replace a line in a file in Python

前端 未结 13 1605
傲寒
傲寒 2020-11-21 07:40

I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory

13条回答
  •  有刺的猬
    2020-11-21 08:00

    Using hamishmcn's answer as a template I was able to search for a line in a file that match my regex and replacing it with empty string.

    import re 
    
    fin = open("in.txt", 'r') # in file
    fout = open("out.txt", 'w') # out file
    for line in fin:
        p = re.compile('[-][0-9]*[.][0-9]*[,]|[-][0-9]*[,]') # pattern
        newline = p.sub('',line) # replace matching strings with empty string
        print newline
        fout.write(newline)
    fin.close()
    fout.close()
    

提交回复
热议问题