pandas 如果 csv 为空,如何不读取_csv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42143249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to NOT read_csv if csv is empty
提问by Devin Liner
Using Python 2.7 and Pandas
使用 Python 2.7 和 Pandas
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:
我必须解析我的目录并绘制一堆 CSV。如果 CSV 为空,脚本会中断并生成错误消息:
pandas.io.common.EmptyDataError: No columns to parse from file
If I have my file paths stored in
如果我将文件路径存储在
file_paths=[]
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
我如何通读每一个并只绘制非空的 CSV?如果我有一个定义为 df=[] 的空数据框,我会尝试以下代码
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))
采纳答案by Chuck
You can use the in built try
and except
syntax to skip over files that return you an error, as follows:
您可以使用内置try
和except
语法来跳过返回错误的文件,如下所示:
Described here: Try/Except in Python: How do you properly ignore Exceptions?
此处描述:Python 中的 Try/Except:您如何正确忽略异常?
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.
这将尝试读取每个文件,如果不成功则继续读取下一个文件。
回答by Boud
I would just catch the appropriate exception, as a catch all is not recommended in python:
我只会捕获适当的异常,因为在 python 中不推荐使用 catch all:
import pandas.io.common
for i in range(0,len(file_paths)):
try:
pd.read_csv(file_paths[i])
except pandas.io.common.EmptyDataError:
print file_paths[i], " is empty"
回答by Nikhil VJ
Note, as of pandas 0.22.0 (that I can be sure of) , the exception raised for empty csv is pandas.errors.EmptyDataError
. And if you're importing pandas like import pandas as pd
, then use pd
instead of pandas
.
请注意,从 pandas 0.22.0(我可以肯定)开始,为空 csv 引发的异常是pandas.errors.EmptyDataError
. 如果您要导入类似 的Pandasimport pandas as pd
,请使用pd
代替pandas
。
If your csv filenames are in an array manyfiles
, then
如果您的 csv 文件名在数组中manyfiles
,则
import pandas as pd
for filename in manyfiles:
try:
df = pd.read_csv(filename)
except pd.errors.EmptyDataError:
print('Note: filename.csv was empty. Skipping.')
continue # will skip the rest of the block and move to next file
# operations on df
I'm not sure if pandas.io.common.EmptyDataError
is still valid or not. Can't find it in reference docs. And I also would advise against the catch-all except:
as you won't be able to know if it's something else causing the issue.
我不确定是否pandas.io.common.EmptyDataError
仍然有效。在参考文档中找不到它。而且我还建议不要使用全面的方法,except:
因为您将无法知道是否是其他原因导致了问题。