with open('core/models.py', 'r') as f: lines = f.readlines() new_lines = [] skip = False for i in range(len(lines)): if skip: if "return" in lines[i]: skip = False continue # Check for duplication of the Priority 0 block if "PRIORITY 0: If they voted" in lines[i]: # If we already added this block recently, skip the next one if it matches if len(new_lines) > 0 and "PRIORITY 0: If they voted" in "".join(new_lines[-10:]): skip = True continue new_lines.append(lines[i]) with open('core/models.py', 'w') as f: f.writelines(new_lines)