Daniel Arges
Daniel Arges

Reputation: 365

is it possible to read an empty csv file?

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?

Upvotes: 3

Views: 3577

Answers (2)

Talendar
Talendar

Reputation: 2087

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

Upvotes: 4

norie
norie

Reputation: 9857

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

Upvotes: 4

Related Questions