Python 3.1.3的csv模块支持Unicode吗?

8

我一直在使用Python 2.6。当我编写一个Python程序来处理来自SQL Server的查询结果(以CSV格式)时,我发现它不支持Unicode。

当我使用csv文件运行程序时,会弹出一个错误提示:

    for row in csvReader:
Error: line contains NULL byte

我使用Ultraedit将csv文件保存为ANSI/ASCII格式后,程序可以正常运行。

我尝试使用编码选项,但失败了:

csvReader = csv.reader(open(fname, mode='rb', encoding='unicode'), delimiter=',')
TypeError: 'encoding' is an invalid keyword argument for this function

csvReader = csv.reader(open(fname, mode='rb', encoding='utf-8'), delimiter=',')
TypeError: 'encoding' is an invalid keyword argument for this function

我想知道 Python 3 是否支持 Unicode 读取。如果可以,这将节省我很多工作。


为什么不直接从Python访问SQL? - Kimvais
Python 3.1.3的open函数绝对支持encoding=参数,因此要么您正在使用不同版本的Python,要么您意外地覆盖了open函数。 - David Wolever
我说过我正在使用Python 2.6。那么Python 3.1.3就不会有这个问题了吗? - lamwaiman1988
Python 3仍然存在这个问题。显然有一个NUL字节会干扰Python,无论是Python 3还是Python 2。 - lamwaiman1988
哦,抱歉,我没有明白你在使用Python 2.6。请看我的更新答案。 - David Wolever
2个回答

7

Python 3 绝对支持 Unicode。我猜测你在读取 CSV 文件时指定了错误的编码(或者没有指定)。请参见:http://docs.python.org/release/3.1.3/library/functions.html#open

尝试这样做:

reader = csv.reader(open("foo.csv", encoding="utf-8"))

编辑:如果您使用的是Python 2.6,您可以通过以下方式实现相同的结果:

import codecs
reader = csv.reader(codecs.open("foo.csv", encoding="utf-8"))

但是,如果你遇到了空字节(null bytes),那么你的文件可能使用"utf-16"编码,因此如果文件不能使用utf-8进行解码,请尝试使用该编码。


我尝试指定编码,但它返回一个错误。请检查我的编辑。 - lamwaiman1988

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接