读取panda中的csv文件时出错[CParserError:标记化数据时出错,C错误:捕获到缓冲区溢出-输入文件格式可能不正确,]

rn0zuynd  于 2023-03-05  发布在  其他
关注(0)|答案(6)|浏览(151)

所以我试着从一个文件夹中阅读所有的csv文件,然后将它们连接起来创建一个大的csv文件(所有文件的结构是相同的),保存它并再次读取它。所有这一切都是使用Pandas完成的。错误发生在读取时。我附上下面的代码和错误。

import pandas as pd
import numpy as np
import glob

path =r'somePath' # use your path
allFiles = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list_ = []
for file_ in allFiles:
    df = pd.read_csv(file_,index_col=None, header=0)
    list_.append(df)
store = pd.concat(list_)
store.to_csv("C:\work\DATA\Raw_data\\store.csv", sep=',', index= False)
store1 = pd.read_csv("C:\work\DATA\Raw_data\\store.csv", sep=',')

错误:-

CParserError                              Traceback (most recent call last)
<ipython-input-48-2983d97ccca6> in <module>()
----> 1 store1 = pd.read_csv("C:\work\DATA\Raw_data\\store.csv", sep=',')

C:\Users\armsharm\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\io\parsers.pyc 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)
    472                     skip_blank_lines=skip_blank_lines)
    473 
--> 474         return _read(filepath_or_buffer, kwds)
    475 
    476     parser_f.__name__ = name

C:\Users\armsharm\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\io\parsers.pyc in _read(filepath_or_buffer, kwds)
    258         return parser
    259 
--> 260     return parser.read()
    261 
    262 _parser_defaults = {

C:\Users\armsharm\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\io\parsers.pyc in read(self, nrows)
    719                 raise ValueError('skip_footer not supported for iteration')
    720 
--> 721         ret = self._engine.read(nrows)
    722 
    723         if self.options.get('as_recarray'):

C:\Users\armsharm\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\io\parsers.pyc in read(self, nrows)
   1168 
   1169         try:
-> 1170             data = self._reader.read(nrows)
   1171         except StopIteration:
   1172             if nrows is None:

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

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

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

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

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

CParserError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file.

我也试过使用csv阅读器:-

import csv
with open("C:\work\DATA\Raw_data\\store.csv", 'rb') as f:
    reader = csv.reader(f)
    l = list(reader)

错误:-

Error                                     Traceback (most recent call last)
<ipython-input-36-9249469f31a6> in <module>()
      1 with open('C:\work\DATA\Raw_data\\store.csv', 'rb') as f:
      2     reader = csv.reader(f)
----> 3     l = list(reader)

Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
niwlg2el

niwlg2el1#

我发现了这个错误,原因是在数据中有一些回车符“\r”,Pandas用它作为行结束符,好像它是“\n”。我想我会在这里张贴,因为这可能是一个常见的原因,这个错误可能会出现。
我找到的解决方案是在read_csv函数中添加lineterminator='\n',如下所示:

df_clean = pd.read_csv('test_error.csv',
                 lineterminator='\n')
wlsrxk51

wlsrxk512#

如果你使用的是python,而且它是一个大文件,你可以使用engine='python',如下所示,应该可以工作。
df = pd.read_csv( file_, index_col=None, header=0, engine='python' )

j9per5c4

j9per5c43#

不是答案,但对于注解来说太长了(不说代码格式)
当您在csv模块中读取它时,它会中断,您至少可以定位错误发生的行:

import csv
with open(r"C:\work\DATA\Raw_data\store.csv", 'rb') as f:
    reader = csv.reader(f)
    linenumber = 1
    try:
        for row in reader:
            linenumber += 1
    except Exception as e:
        print (("Error line %d: %s %s" % (linenumber, str(type(e)), e.message)))

然后在store.csv中查看该行发生了什么。

zbq4xfa0

zbq4xfa04#

将目录更改为CSV

Corpus = pd.read_csv(r"C:\Users\Dell\Desktop\Dataset.csv",encoding='latin-1')
eoxn13cs

eoxn13cs5#

问题出在excel文件的格式上。我们从菜单中选择保存为选项,并将格式从xls改为csv,那么它肯定会工作。

aurhwmvo

aurhwmvo6#

在我的例子中,解决方案是按照下面的答案将编码指定为utf-16:https://stackoverflow.com/a/64516600/9836333

pd.read_csv("C:\work\DATA\Raw_data\store.csv", sep=',', encoding='utf-16')

相关问题