Andres Urrego Angel
Andres Urrego Angel

Reputation: 1932

gspread reading a google sheet file using python 3

I'm using Python 3 running Pycharm and the module gspread to read google sheet files in my google drive. Well, I've followed all steps from this link about how to read a file. Unfortunately, my code here below doesn't work yet.

 import gspread
 from oauth2client.service_account import ServiceAccountCredentials


 scope =['https://docs.google.com/spreadsheets/d/1xnaOZMd2v93tY28h_hsuMnZYXC9YqCfFpQX70lwpN94/edit?usp=sharing']
 credentials = ServiceAccountCredentials.from_json_keyfile_name('distech-c1e26e7150b2.json',scope)
 gc = gspread.authorize(credentials)

 wks = gc.open("POC").sheet1

 for temp in wks:
     print(temp)

How could I read the google sheet file using this module guys? thanks so much

Upvotes: 2

Views: 7884

Answers (1)

Andres Urrego Angel
Andres Urrego Angel

Reputation: 1932

I got it after a deep research I realize two things.

  1. the scope in my code was wrong cause the scope is just one provided by Google API to grant right access permissions under spreadsheet.

    The right scope for me was: scope =['https://spreadsheets.google.com/feeds']

  2. the opener it's just to open the spreadsheet that will return the worksheets within my file.

So solutions thanks to @Pedro Lobito in his post here.

Solution:

I had the same issue with just a couple of spreadsheets on my account, the problem was solved by:

  1. Opening the json key file (projectname-ca997255dada.json)

  2. Find the value of client_email , i.e.: client_email": "[email protected]

  3. Share your sheet(s) with that email

Now my code looks like:

import gspread
from oauth2client.service_account import ServiceAccountCredentials


scope =['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('xxx.json',scope)
gc = gspread.authorize(credentials)

spreadsheet = gc.open("POC")
wks = spreadsheet.worksheet('test1')
wks2 = spreadsheet.worksheet('test2')
out = list()
out = wks.col_values(1)
for temp in out:
    print(out)

Upvotes: 3

Related Questions