在将unicode CSV字符串读入python unicode Descv时遇到问题:
>>> import unicodecsv, StringIO
>>> f = StringIO.StringIO(u'é,é')
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/guy/test/.env/lib/python2.7/site-packages/unicodecsv/__init__.py", line 101, in next
row = self.reader.next()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
我猜这是我如何将unicode字符串转换成StringIO文件的问题?python unicodesv github页面上的示例运行良好:
^{pr2}$用cStringIO尝试我的代码失败了,因为cStringIO不能接受unicode(所以这个例子为什么有用,我不知道!)在
>>> from cStringIO import StringIO
>>> f = StringIO(u'é')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
我需要接受一个来自webtextarea表单域的UTF-8csv格式的输入,因此不能仅仅从文件中读入。在
有什么想法吗?在
unicodecsv
文件为您读取并解码字节字符串。而是传递unicode
字符串。在输出时,您的unicode值将使用配置的编解码器编码为bytestrings。在此外,
cStringIO.StringIO
只能处理由testrings编码的内容,而纯pythonStringIO.StringIO
类很乐意将unicode
值视为字节字符串。在解决方案是在将unicode值放入
StringIO
对象之前对unicode值进行编码:相关问题 更多 >
编程相关推荐