从CSV读取:分隔符必须是字符串,而不是Unicode [英] Reading from CSV: delimiter must be a string, not unicode

查看:809
本文介绍了从CSV读取:分隔符必须是字符串,而不是Unicode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作程序(在一些有帮助的人给我一些关键的建议,在线程)从CSV文件创建模型实例。到目前为止,我一直在使用Python 2.7,并确保没有特殊字符出现在任何地方。目前我需要移动到Unicode。我添加了

 # -  *  - 编码:utf-8  -  *  -  
/ pre>

在我的文件的顶部,一切都很好(我可以在我的代码和评论中使用特殊字符),保存为CSV阅读器例程。也就是说,shell对象这个部分:

  dataReader = csv.reader(open(filename),delimiter =';', quota = $

b $ b

  TypeError:delimiter必须是字符串,而不是unicode 

在阅读一些较旧的问题后,我切换到

$ $ $ $ $ $ $ dataReader = csv.reader(open(filename),delimiter = str(u';'),quotechar = str(u''))

事实上,分隔符将是一个字符串,但我正在得到完全相同的错误。我做错了什么?

解决方案

您的默认编码可能不是最合适的。



指定这样的编码:

  dataReader = csv.reader(open(filename),delimiter = str (u';')。encode('utf-8'),quotechar = str(u'')。encode('utf-8')


I had a working routine (after a few helpful folks gave me some critical advice in this thread) creating model instances from a CSV file. Up to now I have been using Python 2.7 and made sure no special characters appeared anywhere. Currently I need to move to Unicode. I added

# -*- coding: utf-8 -*-

at the top of my files and everything is working nicely (I can use special characters in my code and comments), save for the CSV reader routine. Namely, the shell objects to this part:

dataReader = csv.reader(open(filename), delimiter=';', quotechar='"')

which was working before, with

TypeError: "delimiter" must be string, not unicode

After reading some older questions I switched to

dataReader = csv.reader(open(filename), delimiter=str(u';'), quotechar=str(u'"'))

to enforce the fact that the delimiter would be a string, but I'm getting exactly the same error. What am I doing wrong?

解决方案

Your default encoding is probably not the most appropriate.

Specify the encoding like this :

dataReader = csv.reader(open(filename), delimiter=str(u';').encode('utf-8'), quotechar=str(u'"').encode('utf-8'))

这篇关于从CSV读取:分隔符必须是字符串,而不是Unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆