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