【发布时间】:2019-01-16 13:11:39
【问题描述】:
我正在尝试使用 pandas read_csv 函数结合 skiprows 和 nrows 逐块读取一个巨大的 csv 文件块。我使用 while 循环来做到这一点。
当我到达文件末尾时(跳过的行多于文件中的行数),我得到一个 EmptyDataError。
这本身没有问题,我尝试尝试处理这个问题 - 除了。但是,我这样做的方式不起作用......有人知道为什么吗?在错误处理方面,我是初学者。 这是我的代码:
chunksize = 1000
inputfile = "testfile_with_five_rows.txt"
chunknumber = 0
while True:
try:
data = pd.read_csv(inputfile, skiprows=chunksize*chunknumber, nrows=chunksize)
print(data)
except EmptyDataError:
break
chunknumber+=1
我得到以下 NameError,而不是处理 FileNotFound 异常:
---------------------------------------------------------------------------
EmptyDataError Traceback (most recent call last)
<ipython-input-22-e3736135fc2f> in <module>()
5 try:
----> 6 data = pd.read_csv(inputfile, skiprows=chunksize*chunknumber, nrows=chunksize)
7 print(data)
~/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, doublequote, delim_whitespace, low_memory, memory_map, float_precision)
677
--> 678 return _read(filepath_or_buffer, kwds)
679
~/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
439 # Create the parser.
--> 440 parser = TextFileReader(filepath_or_buffer, **kwds)
441
~/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in __init__(self, f, engine, **kwds)
786
--> 787 self._make_engine(self.engine)
788
~/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in _make_engine(self, engine)
1013 if engine == 'c':
-> 1014 self._engine = CParserWrapper(self.f, **self.options)
1015 else:
~/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in __init__(self, src, **kwds)
1707
-> 1708 self._reader = parsers.TextReader(src, **kwds)
1709
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.__cinit__()
EmptyDataError: No columns to parse from file
During handling of the above exception, another exception occurred:
NameError Traceback (most recent call last)
<ipython-input-22-e3736135fc2f> in <module>()
6 data = pd.read_csv(inputfile, skiprows=chunksize*chunknumber, nrows=chunksize)
7 print(data)
----> 8 except EmptyDataError:
9 break
10
NameError: name 'EmptyDataError' is not defined
【问题讨论】:
-
正如错误所说,您指定的输入文件不存在。检查路径是否正确?其次,您需要从 pandas.errors 导入 EmptyDataError。
-
对不起。我不小心发布了错误的错误信息。我现在编辑了。我在问 NameError。
-
你是否从 pandas.errors 导入 EmptyDataError ?
-
没有。谢谢你!我不知道这是必要的。正如我所说,在错误处理方面我不是专家。这解决了问题!如果你愿意,如果你发布它,我会接受你的提示作为答案,或者如果它被认为对其他程序员不感兴趣,我将删除该问题。
标签: python pandas error-handling