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?