Skip to content

Instantly share code, notes, and snippets.

@danicarrion
Created September 2, 2015 11:01
Show Gist options
  • Save danicarrion/25065a5dc0edd048c73f to your computer and use it in GitHub Desktop.
Save danicarrion/25065a5dc0edd048c73f to your computer and use it in GitHub Desktop.
Export tables from CartoDB as CSV, the_geom being converted to latitude/longitude
[cartodb]
account_name=
api_key=
table_name=
columns=
[file]
name=
import ConfigParser
import csv
import sys
from cartodb import CartoDBAPIKey, CartoDBException
config = ConfigParser.RawConfigParser()
config.read("export.conf")
ACCOUNT_NAME = config.get('cartodb', 'account_name')
API_KEY = config.get('cartodb', 'api_key')
TABLE_NAME = config.get('cartodb', 'table_name')
COLUMNS = config.get('cartodb', 'columns')
FILE_NAME = config.get('file', 'name')
GEOM2LATLON = True
cl = CartoDBAPIKey(API_KEY, ACCOUNT_NAME)
sql = "select %s, ST_X(the_geom) as longitude, ST_Y(the_geom) as latitude from %s" % (COLUMNS, TABLE_NAME,)
COLUMNS = ",".join([COLUMNS, "latitude", "longitude"])
try:
data = cl.sql(sql)
except CartoDBException as e:
print "Error:", e
sys.exit(1)
csv_file = open(FILE_NAME, 'w')
csv_file.write(COLUMNS + "\n")
csv_writer = csv.writer(csv_file)
for row in data["rows"]:
columns = []
for column in COLUMNS.split(","):
try:
columns.append(row[column].encode("utf-8"))
except AttributeError:
columns.append(row[column])
csv_writer.writerow(columns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment