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:
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()