Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda