Python - Loops and Exception Block Else Statements

Troy Williams

2022-05-22

Python - Loops and Exception Block Else Statements

The try/except block has an option else clause. That else clause is executed if an exception is not raised in the block. Loops, also have an else clause. I never thought that I would actually need to use those and thought they were superfluous. Today, I used both. In the following code, I wanted to create a folder, but wanted to make sure that I didn’t create a duplicate folder (i.e. I didn’t want to write files into the same folder).

Consider this code:

from pathlib import Path

def construct_non_duplicate_folder(root:Path, target:str) -> Path:
    folder = root / Path(target)

    for i in range(25):

        try:
            folder.mkdir(parents=True, exist_ok=False)

        except FileExistsError as fe:
            folder = root / Path(f'{target} ({i})')

        else:
            break

    else:
        raise FileExistsError(f'The folder {folder} exists!')


    return folder

On the try/except block (starting around line 8) I have an else statement that breaks the loop. That is, it found a name that didn’t conflict with an existing one. I also have an else block tied to the for loop (line 6) that will only execute if the for loop runs out of numbers. If it does I raise an exception indicating that the folder already exists and there are 26 variations of it already.

This is a very interesting approach and a lot simpler than a bunch of if statements. What we have is a nice mechanism to retry different procedural folder names with a reasonable limit in place. This approach could be applied to file names as well.