How to 'ignore' an error in Python?

Chris Green cl at isbd.net
Sat Apr 29 03:32:25 EDT 2023


Kushal Kumaran <kushal at locationd.net> wrote:
> On Fri, Apr 28 2023 at 04:55:41 PM, Chris Green <cl at isbd.net> 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.
> >
> > I suppose I could test if the directory exists before the os.mkdir()
> > but again that feels a bit clumsy somehow.
> >
> > I suppose also I could use os.mkdirs() with exist_ok=True but again
> > that feels vaguely wrong somehow.
> >
> 
> Why does exist_ok=True feel wrong to you?  This is exactly what it is
> there for.
> 
It was rather using os.mekedirs() to create a single directory that
seemed wrong.  If os.mkdir() had exist_ok=True than that would have
been the obvious way to do it.

-- 
Chris Green
·


More information about the Python-list mailing list