如果csv为空,如何不read_csv [英] how to NOT read_csv if csv is empty

查看:114
本文介绍了如果csv为空,如何不read_csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python 2.7和Pandas

Using Python 2.7 and Pandas

我必须解析我的目录并绘制一堆CSV.如果CSV为空,则脚本将中断并产生错误消息:

I have to parse through my directory and plot a bunch of CSVs. If the CSV is empty, the script breaks and produces the error message:

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

如果我的文件路径存储在

If I have my file paths stored in

file_paths=[]

我如何阅读每一个并且仅绘制非空的CSV?如果我有一个定义为df = []的空数据框,则尝试以下代码

how do I read through each one and only plot the non empty CSVs? If I have an empty dataframe defined as df=[] I attempt the following code

for i in range(0,len(file_paths)):
   if pd.read_csv(file_paths[i] == ""):
      print "empty"
   else df.append(pd.read_csv(file_paths[i],header=None))

推荐答案

您可以使用内置的tryexcept语法跳过返回错误的文件,如下所示:

You can use the in built try and except syntax to skip over files that return you an error, as follows:

此处描述:在Python中尝试/除外:您如何正确忽略异常?

for i in range(0,len(file_paths)):
   try:
       pd.read_csv(file_paths[i])
       ### Do Some Stuff
   except:
       continue
       # or pass

这将尝试读取每个文件,如果失败,则继续下一个文件.

This will attempt to read each file, and if unsuccessful continue to the next file.

这篇关于如果csv为空,如何不read_csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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