CSV文件中为空,使用什么编码

2024-09-28 12:13:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下方法将数据从CSV提取到SQLite db中:

    elif file.endswith('.csv'):
    read_path = os.path.join(dir_read, file)
    with open(read_path,'r',encoding='utf-8') as fin:
        dr = csv.DictReader(fin)
        to_db = [(i['InvoiceNumber'],i['InvoiceType'], i['ChargeType'],i['SupplierID'], i['Net_Amount']) for i in dr]
    
    c.executemany("INSERT INTO mf (InvoiceNumber, InvoiceType, ChargeType, SupplierID, Net_Amount) VALUES (?, ?, ?, ?, ?) ;", to_db)
    con.commit()

这适用于我正在导入的大多数文件(200个文件),但其中一个字段中有一对带有NUL的文件,这不是to_db中的一个字段。我可以在记事本++中看到这一点,一行有一个空字符串,其他所有行都有一个空字符串。 我得到的错误是:

_csv.Error: line contains NULL byte

我尝试过不同的编码(utf-16、le、be),但在所有其他csv文件上都失败了

导入时是否有方法删除这些NULL值并替换为空字符串


Tags: 文件csvtopath方法字符串readdb

热门问题