How to 'ignore' an error in Python?

Mats Wichmann mats at wichmann.us
Fri Apr 28 13:40:53 EDT 2023


On 4/28/23 11:05, MRAB wrote:
> On 2023-04-28 16:55, Chris Green wrote:
>> I'm sure I'm missing something obvious here but I can't see an elegant
>> way to do this.  I want to create a directory, but if it exists it's
>> not an error and the code should just continue.
>>
>> So, I have:-
>>
>>      for dirname in listofdirs:
>>          try:
>>              os.mkdir(dirname)
>>          except FileExistsError:
>>              # so what can I do here that says 'carry on regardless'
>>          except:
>>              # handle any other error, which is really an error

> I'd do this:
> 
>      from contextlib import suppress
> 
>      for dirname in listofdirs:
>          with suppress(FileExistsError):
>              os.mkdir(dirname)

I'm fond of that approach too, though you can't use if it you really 
wanted to do the

           except:
               # handle any other error, which is really an error

If you're okay letting Python just raise whatever other error it found, 
then great!




More information about the Python-list mailing list