Skip to content

Instantly share code, notes, and snippets.

@mcccclean
Created March 20, 2014 11:16
Show Gist options
  • Save mcccclean/9661642 to your computer and use it in GitHub Desktop.
Save mcccclean/9661642 to your computer and use it in GitHub Desktop.
download a google spreadsheet and return it as a list of dicts
import gspread
import getpass
import unicodecsv
def write(filename, values):
f = open(filename, "w")
w = unicodecsv.writer(f, encoding='utf-8')
for row in values:
w.writerow(row)
f.close()
def check(d):
return "".join([d.strip() for d in d])
def grab(user, key, name=None):
filename = "{0}_{1}.csv".format(key, name or 0)
pwd = getpass.getpass()
if pwd:
# get from gdrive
print "Fetching data from Google Docs..."
client = gspread.login(user, pwd)
spreadsheet = client.open_by_key(key)
# fetch sheet
if name:
ws = spreadsheet.worksheet(name)
else:
ws = spreadsheet.get_worksheet(0)
# read data
values = ws.get_all_values()
keys = values[0]
cards = []
for c in values[1:]:
if check(c):
cards.append(dict(zip(keys, c)))
# write to local
write(filename, values)
return cards
else:
with open(filename, "r") as f:
r = unicodecsv.DictReader(f)
return [d for d in r if check(d.values())]
@mcccclean
Copy link
Author

This just is handy to have around in scripts that use card-renderer as google docs spreadsheets is a really good card management tool.

for d in ggrab.grab("user@gmail.com", "0z034vXFr34etcetera"):
    template.card(**d)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment