is it possible to read an empty csv file?

Viewed 890

Seems odd, but for some condition I need to import an empty csv file, as an empty pandas dataframe.

When I try that I get the following error:

EmptyDataError: No columns to parse from file

How to handle it?

2 Answers

Daniel

You could use try/except.

import pandas as pd

try:
      
  df = pd.read_csv('example.csv')
except pd.io.common.EmptyDataError:
  print('File is empty')
else:
  print(df.head())

An easy way to achieve what you want is to simply catch the EmptyDataError raised by pandas.read_csv. Then, you can handle the situation as you see fit (by creating an empty DataFrame, for example):

import pandas as pd

try:
    df = pd.read_csv("empty.csv")
except pd.errors.EmptyDataError:
    df = pd.DataFrame()
Related