简体   繁体   English

CSV DictReader仅获取CSV文件的第一个字符

[英]CSV DictReader only gets the first character of the CSV file

I'm attempting to write a small python script that processes through CSV data. 我正在尝试编写一个处理CSV数据的小型python脚本。 I read the URL and the data is there when I print the variable, but when I parse it using either csv.reader or csv.DictReader it only reads the first character as a field name and then the next character as the value for it. 当读取变量时,我读取了URL,并且数据在那里,但是当我使用csv.reader或csv.DictReader解析它时,它仅读取第一个字符作为字段名称,然后读取下一个字符作为其值。 I don't understand what I'm doing wrong and I would appreciate the help. 我不明白自己在做什么错,我将不胜感激。

Here's my code: 这是我的代码:

import sys
import os
import urllib2
import csv
response = urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?s=YHOO&d=0&e=28&f=2010&g=d&a=3&b=12&c=2009&ignore=.csv')
html = response.read()
informed = csv.DictReader(html)

for row in informed:
  print row

which prints out a dictionary of ['D':'a'] for the first row, and all the rest are character pairs. 它在第一行中打印出['D':'a']字典,其余所有都是字符对。 Any help is appreciated. 任何帮助表示赞赏。 I'm using python 2.6 on Windows. 我在Windows上使用python 2.6。

According to the csv module docs , you need to pass a file or file-like object to the reader, not a string. 根据csv模块docs ,您需要将文件或类似文件的对象传递给阅读器,而不是字符串。 I'm not familiar with what urlopen returns, but you could try passing response to the reader. 我不熟悉urlopen返回的内容,但是您可以尝试将response传递给读者。 Or, you could use a StringIO object which is for just this purpose - html = StringIO.StringIO(response.read()) ought to do it. 或者,您可以使用仅用于此目的的StringIO对象-html html = StringIO.StringIO(response.read())应该这样做。

why not just a regular for loop? 为什么不只是常规的for循环?

   response = urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?s=YHOO&d=0&e=28&f=2010&g=d&a=3&b=12&c=2009&ignore=.csv')
   for line in response.readlines():
        print line.split(',')

You already have the data as string, I don't understand why would you use csv module. 您已经有数据作为字符串,我不明白为什么要使用csv模块。

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

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