Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python: how to do an if/else to read in a csv that can be empty

i want to create a try/except or an if/else statement to create dataframes based on an input csv. but it is possible for the input csv to be blank/empty so if i do a blanket pd.read_csv(file_name)
it will throw an error when the csv is empty.

how can i do this so that:

if pd.read_csv(file_name) is successful:
   new_df = pd.read_csv(file_name)
else:
   new_df = pd.DataFrame() # to set this as an empty data frame

i previously tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

try:
    new_df = pd.read_csv(file_name)
except:
    new_df = pd.DataFrame() # to set this as an empty data frame

this did not work because it always set new_df to an empty df even if the csv was not empty

thanks in advance!!!

>Solution :

Trying to read an empty CSV with pandas.read_csv raises a pandas.errors.EmptyDataError exception, so you can catch that specifically

import pandas as pd


try:
    df = pd.read_csv('my_file.csv')
except pd.errors.EmptyDataError:
    df = pd.DataFrame()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading