简体   繁体   中英

Python try except, try again after executing except statement

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?

To answer the question in the title, you can do this recursively:

def do_stuff(x):
    try:
        stuff(x)
    except SpecificException:
        other_stuff(x)
        do_stuff(x)

If you want to create a file, you can just use:

pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM