简体   繁体   English

从CSV读取:分隔符必须是字符串,而不是unicode

[英]Reading from CSV: delimiter must be a string, not unicode

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. 我有一个工作程序(后一些有用的乡亲给了我一些建议至关重要这个线程)从一个CSV文件创建模型实例。 Up to now I have been using Python 2.7 and made sure no special characters appeared anywhere. 到目前为止,我一直在使用Python 2.7,并确保任何地方都没有出现特殊字符。 Currently I need to move to Unicode. 目前,我需要使用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. 在文件顶部,一切工作正常(我可以在代码和注释中使用特殊字符),但CSV阅读器例程除外。 Namely, the shell objects to this part: 即,shell对此部分对象:

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'))

Happened to me when I switched the code from a file without from __future__ import unicode_literals to one that had it. 当我将代码从一个文件中切换而没有from __future__ import unicode_literals到拥有它的代码时,我发生了。 (python 2.7) (python 2.7)

It changed the default encoding for string and messed with the existing code. 它更改了字符串的默认编码,并与现有代码混淆。

Fixed it by changing from: 通过更改以下内容进行修复:

# worked before using unicode_literals
writer = csv.writer(csvfile, delimiter=';', quotechar='"')  

to

# worked when using unicode_literals
writer = csv.writer(csvfile, delimiter=str(';'), quotechar=str('"'))  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM