Python 2 上的 csv 模块对 Unicode 不友好。您不能将encoding 作为参数传递给它,它不是可识别的参数(仅csv 格式参数被接受为关键字参数)。它不能正确使用 Py2 unicode 类型,因此使用它涉及以二进制模式读取,即使那样,它也只能在换行符每个字符一个字节时才能正常工作。每the csv module docs:
注意:此版本的 csv 模块不支持 Unicode 输入。此外,目前还有一些关于 ASCII NUL 字符的问题。因此,为了安全起见,所有输入都应该是 UTF-8 或可打印的 ASCII;请参阅示例部分中的示例。
如果可能,切换到 Python 3,其中 csv 模块默认与 Py3 的 Unicode 友好的 str 一起使用,绕过 Python 2 的 csv 模块的所有问题,并且可以通过 encoding open 正确。在这种情况下,您的代码将简化为:
with open(r"data/aaa.csv", encoding='utf-16', newline='') as inf:
tsv = csv.reader(inf, delimiter='\t')
# Explicit encoding argument may be needed for TextIOWrapper;
# the rewrapping is done to ensure newline='' is used as the csv module requires
csv.writer(io.TextIOWrapper(sys.stdout.buffer, newline='')).writerows(tsv)
或以 CSV 格式写入 UTF-8 编码文件:
with open(r"data/aaa.csv", encoding='utf-16', newline='') as inf, open(outfilename, "w", encoding='utf-8', newline='') as outf:
tsv = csv.reader(inf, delimiter='\t')
csv.writer(outf).writerows(tsv)
如果失败,请查看the unicodecsv module on PyPI,它应该在 Python 2 上正确处理 Unicode 输入。