How to 'ignore' an error in Python?

Mats Wichmann mats at wichmann.us
Fri Apr 28 12:39:36 EDT 2023


On 4/28/23 09: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 want code here to execute whether or not dirname exists
> 
> 
> Do I really have to use a finally: block?  It feels rather clumsy.

For this specific case, you can use os.makedirs:

os.makedirs(dirname, exist_ok=True)

The mkdir in pathlib also takes the exist_ok flag


As to the way you asked the question, you can use "pass" or the ellipses 
for the "# so what can I do here"




More information about the Python-list mailing list