【问题标题】:How to catch `CParserError` when reading a CSV file读取 CSV 文件时如何捕获“CParserError”
【发布时间】:2015-09-23 13:34:14
【问题描述】:

我想将 CSV 列表读入数据框。但是,当文件的标题行与数据本身不匹配(即元数据或其他空白行)时,我无法捕捉到发生的错误。此错误是“CParserError”(请参阅​​底部的错误消息)。

我目前的解决方案是使用 try-except 语句,

try:
    #read file
except CParserError:
    #give me an error message

但是,这会失败并出现以下错误:

NameError: name 'CParserError' is not defined

我的代码如下。如您所见,我认为我需要多个 except 语句来捕获各种错误。第一个应该检查默认编码类型是否有效(文件永远不会是 utf-8 或 latin-1 以外的任何东西)。如果有标题行,pd.read_csv 会给出我需要捕获的“CParserError”消息(见下文)。然后,如果还有其他杂项问题,我也想了解这些问题。

欢迎任何解决方案,理想情况下可以解释为什么 CParserError 不正确,或者是否可以修改 try-except 逻辑以避免对此的依赖。

谢谢。

files_list = glob.glob('*.csv*')     #get all csvs
files_dict = {}           
for file in files_list:
    try:
        files_dict[file] = pd.read_csv('DFA_me_week27.csv', encoding='utf-8').read() 
    except UnicodeDecodeError:    
        files_dict[file] = pd.read_csv('DFA_me_week27.csv', encoding='Latin-1').read()
    except CParserError:
        print(file, 'failed: check for header rows')
    except:
        print(file, 'failed: some other error occurred')

尝试解析带有标题的 CSV 文件时的错误消息:

CParserError                              Traceback (most recent call last)
<ipython-input-15-e454c053d675> in <module>()
----> 1 pd.read_csv('DFA_me_week27.csv')

C:\Users\john.lwli\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, dialect, compression, doublequote, escapechar, quotechar, quoting, skipinitialspace, lineterminator, header, index_col, names, prefix, skiprows, skipfooter, skip_footer, na_values, na_fvalues, true_values, false_values, delimiter, converters, dtype, usecols, engine, delim_whitespace, as_recarray, na_filter, compact_ints, use_unsigned, low_memory, buffer_lines, warn_bad_lines, error_bad_lines, keep_default_na, thousands, comment, decimal, parse_dates, keep_date_col, dayfirst, date_parser, memory_map, float_precision, nrows, iterator, chunksize, verbose, encoding, squeeze, mangle_dupe_cols, tupleize_cols, infer_datetime_format, skip_blank_lines)
    463                     skip_blank_lines=skip_blank_lines)
    464 
--> 465         return _read(filepath_or_buffer, kwds)
    466 
    467     parser_f.__name__ = name

C:\Users\john.lwli\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    249         return parser
    250 
--> 251     return parser.read()
    252 
    253 _parser_defaults = {

C:\Users\john.lwli\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
    708                 raise ValueError('skip_footer not supported for iteration')
    709 
--> 710         ret = self._engine.read(nrows)
    711 
    712         if self.options.get('as_recarray'):

C:\Users\john.lwli\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
   1157 
   1158         try:
-> 1159             data = self._reader.read(nrows)
   1160         except StopIteration:
   1161             if nrows is None:

pandas\parser.pyx in pandas.parser.TextReader.read (pandas\parser.c:7403)()

pandas\parser.pyx in pandas.parser.TextReader._read_low_memory (pandas\parser.c:7643)()

pandas\parser.pyx in pandas.parser.TextReader._read_rows (pandas\parser.c:8260)()

pandas\parser.pyx in pandas.parser.TextReader._tokenize_rows (pandas\parser.c:8134)()

pandas\parser.pyx in pandas.parser.raise_parser_error (pandas\parser.c:20720)()

CParserError: Error tokenizing data. C error: Expected 2 fields in line 12, saw 12

【问题讨论】:

  • 为什么不直接跳过标题?
  • 您能解释一下您的意思吗?我不确定这会是一件容易的事,因为有时标题的格式不同。例如有时会有 12 行和 2 列的标题行;其他时候只有一行。
  • 12 行 2 列的标题行是什么意思?你也可以error_bad_lines=False 但这会忽略所有坏行
  • 如果你想捕捉CParserError,请使用except pd.parser.CParserError:
  • pd.parser.CParserError 解决了我的问题,谢谢

标签: python python-3.x pandas


【解决方案1】:

如果你有 import pandas as pd,你可以排除这样的错误(pandas 0.19):

except pd.parser.CParserError:

【讨论】:

  • 错误我有“pandas.errors.ParserError: 错误标记数据。C 错误: 预计第 22 行中有 7 个字段,看到 8”
【解决方案2】:

我用 from pandas.parser import CParserError 我得到了 FutureWarning: The pandas.parser module is deprecated and will be removed in a future version. Please import from the pandas.io.parser instead 所以 from pandas.io.parser import CParserError 被推荐。

我使用的是 Python 3.6,我的 pandas 版本是 0.20.3


但是,当我使用 from pandas.io.parser import CParserError 时,我得到了 ModuleNotFoundError: No module named 'pandas.io.parser'

【讨论】:

  • 这里一样,这些答案都不起作用。编辑:这有效:except pd.parser.CParserError:
【解决方案3】:

我不想说显而易见的,但是...

from pandas.parser import CParserError

FutureWarning:pandas.parser 模块已弃用,将在未来版本中删除。请改用以下内容

import from the pandas.io.parser

【讨论】:

    猜你喜欢
    • 2012-08-13
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2018-05-12
    • 2015-10-23
    • 2020-06-20
    • 2017-01-07
    相关资源
    最近更新 更多