Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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)
over 4 years ago · Santiago Trujillo Report

0

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')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!