DictReader错误:预期的字符串或Unicode对象,找到列表 [英] DictReader error: expected string or Unicode object, list found
本文介绍了DictReader错误:预期的字符串或Unicode对象,找到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试阅读具有以下权限的Google表格文档:
I am trying to read a google sheet document with permissions like this:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8')]
response = opener.open(
"https://docs.google.com/spreadsheets/d/ID/export?format=csv"
)
csv_records = unicodecsv.reader(response, encoding='utf-8')
translations = csv.DictReader(csv_records)
for row in translations:
print row["age"]
但是,我得到一个错误:expected string or Unicode object, list found
可能是字段名称.
however, I get an error : expected string or Unicode object, list found
probably for the fieldnames.
怎么了?
堆栈跟踪:
File "/Users/me/projects/ad_copy.py", line 68, in create_copies
for row in translations
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 107, in next
self.fieldnames
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 90, in fieldnames
self._fieldnames = self.reader.next()
TypeError: expected string or Unicode object, list found
打印
print translations
print csv_records
<csv.DictReader instance at 0x11163fa28>
<unicodecsv.py2.UnicodeReader object at 0x11160da50>
推荐答案
据我了解,unicodecsv返回一个列表,以您的情况为csv_records
.
As far as I understand, unicodecsv returns a list, in your case csv_records
.
这取自 github自述文件:
>>> import unicodecsv as csv
>>> from io import BytesIO
>>> f = BytesIO()
>>> w = csv.writer(f, encoding='utf-8')
>>> _ = w.writerow((u'é', u'ñ'))
>>> _ = f.seek(0)
>>> r = csv.reader(f, encoding='utf-8')
>>> next(r) == [u'é', u'ñ']
True
最后看一下比较.
您将此返回列表放入csv.DictReader()
,这是不必要的,因为结果已经在csv_records
之内.
You put this returned list into a csv.DictReader()
, which is not necessary, since the result already is within csv_records
.
打印出此变量,看看里面有什么.
Print out this variable, see what is inside.
这篇关于DictReader错误:预期的字符串或Unicode对象,找到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文