Can you "restart" the current iteration of a Python loop?

Solution 1:

You could put your try/except block in another loop and then break when it succeeds:

for row in rows:
    while True:
        try:
            something
            break
        except Exception: # Try to catch something more specific
            pass

Solution 2:

You could make rows an iterator and only advance when there is no error.

it = iter(rows)  
row = next(it,"")
while row:
    try:
        something
        row = next(it,"")
    except:
       continue

On a side note, if you are not already I would catch specific error/errors in the except, you don't want to catch everything.

If you have Falsey values you could use object as the default value:

it = iter(rows)
row, at_end = next(it,""), object()
while row is not at_end:
    try:
        something
        row = next(it, at_end)
    except:
        continue

Solution 3:

Although I wouldn't recommend that, the only way to do this is to make a While (True) Loop until it gets something Done.

Bear in mind the possibility of a infinite loop.

for row in rows:
    try:
        something
    except:
        flag = False
        while not flag:
            try: 
               something
               flag = True
            except:
               pass

Solution 4:

Have your for loop inside an infinite while loop. Check the condition where you want to restart the for loop with a if else condition and break the inner loop. have a if condition inside the while loop which is out side the for loop to break the while loop. Like this:

    while True:
      for row in rows:
        if(condition)
        .....
        if(condition)
         break
   if(condition)
     break