Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing empty file with no columns

Tags:

python

parsing

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 be able to parse a text file containing nothing, and return an empty data frame but it doesn't allow me to do that and has an error on the line reading the file using python pandas. Is there other way to do it?

import pandas as pd

def read_data(file):
    df = pd.read_csv(file, delim_whitespace=True)
    return df

ERROR:

pandas.io.common.EmptyDataError: No columns to parse from file
like image 441
iteong Avatar asked Oct 22 '25 01:10

iteong


2 Answers

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

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

    return df
like image 138
Soviut Avatar answered Oct 24 '25 14:10

Soviut


Just eat the exception and make an empty df:

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

    return df
like image 36
aghast Avatar answered Oct 24 '25 14:10

aghast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!