使用 unicodecsv 模块读取 csv 时出现 \ufeff

Em *_* Ae 3 python csv unicode python-3.9

我有以下代码

import unicodecsv
CSV_PARAMS = dict(delimiter=",", quotechar='"', lineterminator='\n')
unireader = unicodecsv.reader(open('sample.csv', 'rb'), **CSV_PARAMS)
for line in unireader:
    print(line)

Run Code Online (Sandbox Code Playgroud)

它打印

['\ufeff"003', 'word one"']
['003,word two']
['003,word three']
Run Code Online (Sandbox Code Playgroud)

CSV 看起来像这样

"003,word one"
"003,word two"
"003,word three"

Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么第一行有\ufeff(我相信这是一个文件标记)。而且,"在第一行的开头。

CSV 文件是来自客户端的,所以我无法指示他们如何保存文件等。希望修复我的代码,以便它可以处理编码。

注意:我已经尝试过encoding='utf8',CSV_PARAMS但没有解决问题

Mar*_*nen 9

encoding='utf-8-sig'将删除某些文件中用作 UTF-8 签名的 UTF-8 编码的 BOM(字节顺序标记):

import unicodecsv

with open('sample.csv','rb') as f:
    r = unicodecsv.reader(f, encoding='utf-8-sig')
    for line in r:
        print(line)
Run Code Online (Sandbox Code Playgroud)

输出:

['003,word one']
['003,word two']
['003,word three']
Run Code Online (Sandbox Code Playgroud)

但为什么要使用第三方的unicodecsvPython 3 呢?内置csv模块正确处理 Unicode:

['003,word one']
['003,word two']
['003,word three']
Run Code Online (Sandbox Code Playgroud)