How to read an empty csv file and convert into an excel.?

Viewed 80

I have 3 csv files in folder and iterate through each file and convert each file into xlsx sheet.One of the csv file was 0kb(Empty file). My Code :

for file in glob.glob("*.csv"):
 df=pd.read_csv(file)
 df.to_excel(file+".xlsx",sheet_name=file,index=False)

Error : No columns to parse from the file

1 Answers

I would solve this by catching the exception that occurs when the file is empty, and creating an empty dataframe to output to the Excel file in that case.

import pandas as pd
import glob

for file in glob.glob("*.csv"):
    try:
        df = pd.read_csv(file)
    except pd.errors.EmptyDataError:
        df = pd.DataFrame()
    df.to_excel(file+".xlsx", sheet_name=file, index=False)
Related