简体   繁体   中英

How can we load a pandas dataframe using an empty csv file and how can we check that the csv file choosen by us for loading the dataframe is empty?

I am working on a project in which I want to load a dataframe using the csv file and check if the file from which I want to load the dataframe is empty or not. If the csv file is empty then as soon as the statement df=pd.read_csv(file.csv) is encountered , I get the error pandas.errors.EmptyDataError: No columns to parse from file Please help me

#custom error class defined correctly
try:
    #file.csv is an empty csv file
   df=pd.read_csv(file.csv)
   if df:
        print("Dataframe loaded successfully!!")
   else:
        raise Empty_csv_file_Error("The csv file is empty!!")
except Empty_csv_file_Error as e:
    print(e.msg)

Error encountered while loading the dataframe using empty csv file :- pandas.errors.EmptyDataError: No columns to parse from file

The pandas error is telling you that the file is empty, so just catch it:

import pandas as pd

try:
    #file.csv is an empty csv file
   df=pd.read_csv(file.csv)
except pd.errors.EmptyDataError:
    print("The CSV file is empty")
else:
    print("Dataframe loaded successfully!!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM