Python捕获异常“Pandas.错误.解析器错误:标记化数据时出错,C错误”

ltskdhd1  于 2023-01-07  发布在  Python
关注(0)|答案(2)|浏览(226)

我正面临着我的故障csv输入文件整个阅读的问题,我可以通过添加**“error_bad_lines=False”**在我的read_csv函数中删除这些来处理。
但我需要报告这些文件,这是造成的问题,我假设我需要捕捉该异常。我尝试使用

except pd.parser.CParserError

以及

except ExceptionSubclass as exceptionsubclass:

在互联网上搜索后,在这两种情况下,我不能赶上这个异常,如果你有任何想法如何报告所有的故障文件,请让我知道。
我得到的错误:

Traceback (most recent call last):
  File "main.py", line 134, in reading_csv
    df = pd.read_csv(absolute_path_of_file, sep=',', dtype=str, keep_default_na=False)
    data = self._reader.read(nrows)
  File "pandas/_libs/parsers.pyx", line 890, in pandas._libs.parsers.TextReader.read (pandas/_libs/parsers.c:10862)
  File "pandas/_libs/parsers.pyx", line 912, in pandas._libs.parsers.TextReader._read_low_memory (pandas/_libs/parsers.c:11138)
  File "pandas/_libs/parsers.pyx", line 966, in pandas._libs.parsers.TextReader._read_rows (pandas/_libs/parsers.c:11884)
  File "pandas/_libs/parsers.pyx", line 953, in pandas._libs.parsers.TextReader._tokenize_rows (pandas/_libs/parsers.c:11755)
  File "pandas/_libs/parsers.pyx", line 2184, in pandas._libs.parsers.raise_parser_error (pandas/_libs/parsers.c:28765)
pandas.errors.ParserError: Error tokenizing data. C error: Expected 7 fields in line 22, saw 8
yws3nbqq

yws3nbqq1#

尝试使用except pd.errors.ParserError而不是except pd.parser.CParserError
这是Pandas饲养的exception

pgky5nke

pgky5nke2#

答案是here

from pandas.errors import ParserError
try:
    ...
except ParserError:
    ...

或简单

except pd.errors.ParserError  as text_exception:

相关问题