Skip to content Skip to sidebar Skip to footer

Parsing Empty File With No Columns

I have a function that reads a text file and then parses it into a data frame. Usually the input file will be something like this: A B M 1 2 100 2 1 20 I would like to

Solution 1:

There are ways you can validate that a file is empty or formatted incorrectly. However, you can also just catch the exception and return an empty data frame.

from pandas.io.common import EmptyDataError

defread_data(file):
    try:
        df = pd.read_csv(file, delim_whitespace=True)
    except EmptyDataError:
        df = pd.DataFrame()

    return df

Solution 2:

Just eat the exception and make an empty df:

defread_data(file):
    try:
        df = pd.read_csv(file, delim_whitespace=True)
    except pandas.io.common.EmptyDataError:
        df = pd.DataFrame()

    return df

Post a Comment for "Parsing Empty File With No Columns"