Search code examples
pythoncsvgoogle-fusion-tables

Can I use Python's CSV reader with Google Fusion Tables?


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


Solution

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