通过 Paramiko 从 SFTP 服务器将 CSV 文件读入 Pandas 失败,并显示“'utf-8'编解码器无法解码字节...在位置...:无效的起始字节”

2023-12-09

我正在尝试使用 Paramiko 从 SFTP 服务器将 CSV 文件读入 Pandas:

with sftp.open(path + file.filename) as fp:
    fp_aux = pd.read_csv(fp, separator = '|')

但是当尝试它时,它会抛出以下错误:

“utf-8”编解码器无法解码位置 73 中的字节 0xa3:起始字节无效

我尝试过不同的编码将不同的参数传递给encoding的论证pd.read_csv函数(unicode_escape、latin-1、latin1、latin、utf-8...)。我也尝试过engine='python'但到目前为止还没有运气。还有什么我可以尝试的吗?如果没有,我如何忽略该错误并继续下一行或下一个 df?

仅当我尝试从 SFTP 服务器读取时才会发生这种情况,如果我从本地磁盘读取它则工作正常。

错误的完整调用堆栈:

UnicodeDecodeError                        Traceback (most recent call last)
pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_tokens()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_with_dtype()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._string_convert()

pandas\_libs\parsers.pyx in pandas._libs.parsers._string_box_utf8()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa3 in position 83: invalid start byte

During handling of the above exception, another exception occurred:

UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-41-53537b824736> in <module>
      1 with sftp.open(r'/Debtopdcarich/Mandatory File/MandatoryFile_190721.csv') as fp:
----> 2     fp_aux = (pd.read_csv(fp, encoding='iso-8859-1', sep='|'))

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options)
    603     kwds.update(kwds_defaults)
    604 
--> 605     return _read(filepath_or_buffer, kwds)
    606 
    607 

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    461 
    462     with parser:
--> 463         return parser.read(nrows)
    464 
    465 

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
   1050     def read(self, nrows=None):
   1051         nrows = validate_integer("nrows", nrows)
-> 1052         index, columns, col_dict = self._engine.read(nrows)
   1053 
   1054         if index is None:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
   2054     def read(self, nrows=None):
   2055         try:
-> 2056             data = self._reader.read(nrows)
   2057         except StopIteration:
   2058             if self._first_chunk:

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader.read()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._read_rows()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_column_data()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_tokens()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_with_dtype()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._string_convert()

pandas\_libs\parsers.pyx in pandas._libs.parsers._string_box_utf8()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa3 in position 83: invalid start byte

Pandas 似乎对 Paramiko 文件类对象 API 感到困惑。它不使用它的encoding参数,当与 Paramiko 文件类对象一起出现时。

快速而肮脏的解决方案是将远程文件读取到内存中的类似文件的对象并将其呈现给 Pandas。然后encoding使用参数。

flo = BytesIO()
sftp.getfo(path + file.filename, flo)
flo.seek(0)
pd.read_csv(flo, separator = '|', encoding='iso-8859-1')

更有效的方法可能是在 Paramiko 文件类对象之上构建一个包装类,并使用 Pandas 可以使用的 API。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 Paramiko 从 SFTP 服务器将 CSV 文件读入 Pandas 失败,并显示“'utf-8'编解码器无法解码字节...在位置...:无效的起始字节” 的相关文章

随机推荐