Search code examples
pythonpandasdataframeemptydatatext

How to make pandas read empty data file as an empty dataframe?


We can assign an empty dataframe with pandas.

import pandas as pd
zero = pd.DataFrame()
zero
Empty DataFrame
Columns: []
Index: []

The zero dataframe is empty containing nothing in it,create a empty data file containing nothing in it.

fh = open('/tmp/test.txt','w')
fh.close()

The file /tmp/test.txt is empty.

newzero = pd.read_csv('/tmp/test.txt',header=None)
pandas.errors.EmptyDataError: No columns to parse from file

How to make pandas read an empty file and assign it as a empty dataframe such as zero shows ? Is there a way to add some argument to make the below commands running without error info.

newzero = pd.read_csv('/tmp/test.txt',header=None,add some argument)
newzero
Empty DataFrame
Columns: []
Index: []

Solution

  • You can catch exception and create a empty data frame

    import pandas as pd
    zero = pd.DataFrame()
    fh = open('/tmp/test.txt','r')
    fh.close()
    try:
        newzero = pd.read_csv('test.txt',header=None)
    except pd.errors.EmptyDataError:
        newzero = pd.DataFrame()