pythonpandas

Add exception handler and continue code execution


I have this Python code used to read files:

import pandas as pd

metadata_files = []
csv_df = pd.DataFrame()
meta_files_list = (pd.read_csv(file, encoding='utf-8', sep=";") for file in metadata_files)
meta_files_df = pd.concat(meta_files_list, ignore_index=True)

Sometimes I get an exception because files are empty at the line pd.concat.

How I can properly process this exception and continue program execution?

I want to send a message somehow to process this issue.


Solution

  • You could use try and except syntax of python:

    metadata_files = []
    csv_df = pd.DataFrame()
    meta_files_list = (pd.read_csv(file, encoding='utf-8', sep=";") for file in 
    metadata_files)
    try:
      meta_files_df = pd.concat(meta_files_list, ignore_index=True)
    except:
      print("could not concat")
    

    Simply add what you want to do in the case of concat not working.