There is a code that works only with the data in the file.

import re f = open('12345') lines = f.readlines() f.close() f = open('12345', 'w') for line in lines: r = re.search(r'^.*("deactivated":"banned"|"deactivated":"deleted").*$', line).group(0) if line != r: f.write(line) print(r) f.close() 

The problem is as follows. It is necessary to give the exact string in "r", I do this with the help of ".group (0)", but as soon as an exception is found, "r" becomes an object "None", everything crashes. I tried:

 try: if line != r: f.write(line) print(r) except AttributeError: continue 

No results. Doesn't want to catch the error in any way:

 AttributeError: 'NoneType' object has no attribute 'group' 
  • Regular, by the way, can be simplified: r'"deactivated":"(banned|deleted)"' . - Alexey Ukolov
  • And .group(0) completely useless - it’s enough to compare r with None, you are interested in the fact that there is no match, None means exactly this: if re.search(r'"deactivated":"(banned|deleted)"') == None - Alexey Ukolov
  • Ideally, I need the fact of comparing the string, and then with the "None". You prompted the right decision, the regular schedule can be dropped for the time being. - Talisman
  • Actually, the error itself lies in the fact that the try line should be moved one line higher: try: r=re.searc(...).group(0)... - andy.37

1 answer 1

You don't need regular expressions here, finding the substring is enough, which is faster * and simpler than regulars:

 f = open('12345') lines = f.readlines() f.close() f = open('12345', 'w') for line in lines: if '"deactivated":"banned"' not in line and '"deactivated":"deleted"' not in line: f.write(line) print(r) f.close() 

And the exception is not handled because you, for some reason, did not wrap the string that actually throws it.

* Need to test, of course. It is possible that a regular expression will be faster than double searching for a substring.

  • Error ... Not really necessary. It is necessary that he exclude these lines, and not choose. - Talisman
  • Well, change the check to not in . Do such things need to chew? I'll update the answer now ... - Alexey Ukolov
  • just didn't work ... - Talisman
  • What just didn't work? I updated the answer a few minutes ago by changing the validation logic. - Alexey Ukolov
  • Yes, thanks, I saw) instead of 'or' 'and' stands. Thank you so much for your help, mildsdar) - Talisman