解析没有列的空文件 [英] parsing empty file with no columns

查看:179
本文介绍了解析没有列的空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个读取文本文件,然后将其解析为数据帧的函数.

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

我希望能够解析一个不包含任何内容的文本文件,并返回一个空的数据框,但它不允许我这样做,并且在使用python pandas读取文件的行上出现了错误.还有其他方法吗?

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

错误:

pandas.io.common.EmptyDataError: No columns to parse from file

推荐答案

有几种方法可以验证文件为空或格式错误.但是,您也可以捕获异常并返回一个空白数据框.

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

这篇关于解析没有列的空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆