silentninja89
silentninja89

Reputation: 201

Python If error exist then ignore and keep going with the rest of the code

I made the following code that consumes multiple reports on a specific folder:

import pandas as pd
import glob

##some code before

all_files = glob.glob("CONTROL_REPORT*")
lib = []

for filename in all_files:
     df = pd.read_csv(filename, index_col=None, header=0)
     lib.append(df)

ap_control = pd.concat(lib, axis=0, ignore_index=True)
ap_control = ap_control[['Column1','Column2','Column3','Column4','Column5']]

##some code after

However there are instances that the control_report doesn't exist on the folder hence I would like to add an exception that if there's an error on this part of the code to ignore and keep going with the rest of it.

Thanks in advance

Upvotes: 0

Views: 568

Answers (2)

Hima
Hima

Reputation: 12054

add try--catch---exception block

for filename in all_files:
     try:
         df = pd.read_csv(filename, index_col=None, header=0)
     except:
         continue
     lib.append(df)

Upvotes: 1

Alejandro Garcia
Alejandro Garcia

Reputation: 26

You'll need to use the Try-Except statement for this

https://www.w3schools.com/python/python_try_except.asp

Regards

Upvotes: 0

Related Questions