문제

I'm trying to read data from Google Fusion Tables API into Python using the csv library. It seems like querying the API returns CSV data, but when I try and use it with csv.reader, it seems to mangle the data and split it up on every character rather than just on the commas and newlines. Am I missing a step? Here's a sample I made to illustrate, using a public table:

#!/usr/bin/python

import csv
import urllib2, urllib

request_url = 'https://www.google.com/fusiontables/api/query' 
query = 'SELECT * FROM 1140242 LIMIT 10'

url = "%s?%s" % (request_url, urllib.urlencode({'sql': query}))
serv_req = urllib2.Request(url=url)
serv_resp = urllib2.urlopen(serv_req)

reader = csv.reader(serv_resp.read())

for row in reader:
    print row #prints out each character of each cell and the column headings

Ultimately I'd be using the csv.DictReader class, but the base reader shows the issue as well

도움이 되었습니까?

해결책

csv.reader() takes in a file-like object.

Change

reader = csv.reader(serv_resp.read()) 

to

reader = csv.reader(serv_resp)

Alternatively, you could do:

reader = csv.DictReader(serv_resp)

다른 팁

It's not the CSV module that's causing the problem. Take a look at the output from serv_resp.read(). Try using serv_resp.readlines() instead.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top