Created
March 20, 2014 11:16
-
-
Save mcccclean/9661642 to your computer and use it in GitHub Desktop.
download a google spreadsheet and return it as a list of dicts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This just is handy to have around in scripts that use card-renderer as google docs spreadsheets is a really good card management tool.