I'm trying to execute a statement, but if it fails I want to execute the except statement and after I want to execute the try again. I know I can use loops, but I'm looking for a more elegant solution.
In my use case I try to save a file to a folder but if I get the FileNotFoundError I want to create the folder in the except and go to the try again.
from pathlib import Path
import os
folder = Path('folder')
df = [a,b,c]
try:
df.to_feather(folder / 'abc.ftr')
except:
os.makedirs(folder)
df.to_feather(folder / 'abc.ftr')
But in this case I would repeat the df.to_feather(folder / 'abc.ftr')
statement. This get's annoying if the statement gets larger and I want to refrain for building a function for this.
Another way could be:
if folder not in os.listdir():
os.makedirs(folder)
df.to_feather(folder / 'abc.ftr')
Would this be the 'proper' way to tackle this?
Since python3.2
os.makedirs
has optional exist_ok
argument, which by default is False
. When set True
and os.makedirs
is instructed to create catalog(s) which is(are) already existing it is no-operation. Thus in place of
if folder not in os.listdir():
os.makedirs(folder)
df.to_feather(folder / 'abc.ftr')
you can just do
os.makedirs(folder, exist_ok=True)
df.to_feather(folder / 'abc.ftr')