Python:C 引擎不支持正则表达式分隔符

Tyl*_*wan 6 python regex pandas

尝试将一堆 csv 上传到数据库。csv 不一定总是用逗号分隔,因此我使用正则表达式来确保使用正确的分隔符。然后我添加了

error_bad_lines=False
Run Code Online (Sandbox Code Playgroud)

为了处理 CParserError:错误标记数据。C 错误:第 127 行中预期有 3 个字段,但看到了 4 个字段,这导致我收到此错误

ValueError: Falling back to the 'python' engine because the 'c' engine does not support regex separators, but this causes 'error_bad_lines' to be ignored as it is not supported by the 'python' engine. 
Run Code Online (Sandbox Code Playgroud)

对于以下代码

有解决方法吗?

import psycopg2
import pandas as pd
import sqlalchemy as sa
csvList = []
tableList = []
filenames = find_csv_filenames(directory)
for name in filenames:  
    lhs, rhs = str(name).split(".", 1)
    print name
    dataRaw = pd.read_csv(name,sep=";|,",chunksize=5000000, error_bad_lines=False)
    for chunk in dataRaw:
        chunk.to_sql(name = str(lhs),if_exists='append',con=con) 
Run Code Online (Sandbox Code Playgroud)

小智 9

根据此链接 Pandas-link中的 pandas 参数 ,如果分隔符超过一个字符,则需要将引擎参数添加为'python'

尝试这个,

dataRaw = pd.read_csv(name,sep=";|,",engine ='python',chunksize=5000000,
error_bad_lines=False)
Run Code Online (Sandbox Code Playgroud)


Ant*_*pov 1

如果您可以预处理并更改文件,请尝试更改;分隔符,以制作干净的 csv 文件。您可以通过fileinput就地更改它来做到这一点:

import fileinput

for line in fileinput.FileInput('your_file', inplace=True):
    line = line.replace(';', ',')
    print(line, end='')
fileinput.close()
Run Code Online (Sandbox Code Playgroud)

然后您可以read_csvc引擎一起使用并使用参数error_bad_lines,或者您也可以使用该循环对它们进行预处理。

注意:如果您想备份文件,可以使用backup参数FileInput