Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python to Remove All Lines Matching Regex

I'm attempting to remove all lines where my regex matches(regex is simply looking for any line that has yahoo in it). Each match is on it's own line, so there's no need for the multiline option.

This is what I have so far...

import re
inputfile = open('C:\\temp\\Scripts\\remove.txt','w',encoding="utf8")

inputfile.write(re.sub("\[(.*?)yahoo(.*?)\n","",inputfile))

inputfile.close()

I'm receiving the following error:

Traceback (most recent call last): line 170, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or buffer

like image 664
MrMr Avatar asked Jun 20 '13 18:06

MrMr


1 Answers

Use fileinput module if you want to modify the original file:

import re
import fileinput
for line in fileinput.input(r'C:\temp\Scripts\remove.txt', inplace = True):
   if not re.search(r'\byahoo\b', line):
      print(line, end="")
like image 168
Ashwini Chaudhary Avatar answered Sep 25 '22 02:09

Ashwini Chaudhary