Saturday, March 19, 2016

How I was finally able to use Python to access and update google sheets

Connecting to google sheets via Python

So after hours of searching the web looking for how to connect to a google sheet, I was finally able to connect.

Found many articles that referenced deprecated modes of connecting,
  1. Get access to the Google  API from Google Developer Console and downloading the JSON file with your secret information, Secret Email, key etc.
  2. Don't forget to share the file with the email address in your JSON credentials - Took a long time to realize why I could not successfully access the file.
  3. The following code snippets could be refined by breaking up the code into methods, but currently I just worked it out a sequentially processed file. I will clean the code up now that things are operational.
  4. This code uses JSON, gspread and oauth2client packages
  5. Use pip install for gspread and oauth2client
  6. Links I need to credit are many, but the major is here and here.


This is a working script in Python 2.7 on Windows 7 running in Idle.

import json
import gdata.spreadsheet.service
import gspread
from oauth2client.client import SignedJwtAssertionCredentials

json_key = json.load(open('My Project-a0fcf0086cb5.json'))

print 'got key'
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'],scope)

gc = gspread.authorize(credentials)
print('Authentication complete')

wb2 = gc.open("test").sheet1
values_list = (wb2.col_values(1))
print('wbs vals loaded')
print (values_list)


No comments:

Post a Comment