0

I am looking to do the following:

  1. Iterate through a file
  2. assert that a specific condition is not in each line
  3. if it returns false, log the offending row
  4. Continue through the entire file

This is what I currently have:

import logging

with open('checkpoints-results.log') as file:
  for row in file:
    assert '"status":"Unresolved"' not in row, logging.warning(row)

Right now it's going through and grabbing the first occurrence, but then it stops.

Am I missing something for continuing until I reach the end of the file?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
kmancusi
  • 591
  • 3
  • 20
  • 4
    `assert` is meant to be used as a **hard failure** because some precondition of your code has been violated. If you just want to log and keep going, just use a plain old `if` statement. – 0x5453 Sep 24 '21 at 15:00
  • _Why_ are you using `assert` there? – jonrsharpe Sep 24 '21 at 15:00
  • 1
    Elaborating a bit more on what @0x5453 said, i think it would be a good read https://stackoverflow.com/questions/5142418/what-is-the-use-of-assert-in-python – Alexander Santos Sep 24 '21 at 15:02

1 Answers1

2

assert will raise an exception (AssertionError) if the condition is not met. If an exception is raised, it halts the current control flow and raises until it's caught (or until the program terminates). Typically you use an assert to indicate something that has gone unexpectedly wrong such that your program should immediately terminate.

What I think you want to do is use a simple if statement:

import logging

with open('checkpoints-results.log') as file:
    for row in file:
        if '"status":"Unresolved"' in row:
            logging.warning(row)
            continue
        # do other stuff with the row?
Samwise
  • 68,105
  • 3
  • 30
  • 44