How to use PyDrive2 to access google sheets inside a data frame in python

Search for a command to run...

No comments yet. Be the first to comment.
Here's the TLDR. Create a file to where all the methods will be present. // s3.js import * as AWS from '@aws-sdk/client-s3'; const bucket = process.env.AWS_BUCKET_NAME; const region = process.env.AWS_REGION; const endpoint = process.env.AWS_ENDPOIN...
Back in my previous company, we ran into issues where our MongoDB server became very slow and affected all our queries. Fortunately, we used Atlas and Profiler was available to us to analyse what was going on. Here are some things we looked at. High...

Uploading file to google drive requires the following steps: Authenticate with google drive Uploading a file to a specific folder by the name of the folder If the folder does not exist, we need to create the folder first Finally, upload the file....
While naming variables, functions and classes is one of the hardest things to do as a programmer, writing comments is also hard. It’s easier to express our logic in code vs English. Let’s look at the best ways to write comments in code. YAGNI — You a...

With an increasing number of users using google sheets to maintain data, it has become essential to access google sheets in your development environment.
You have a few options:
Use API from services like sheetsu, sheety, etc
Use Official Google sheets API documented here https://developers.google.com/sheets/api/quickstart/python
Use a python wrapper library like PyDrive2 (PyDrive is not maintained anymore)
In this blog, we will look at PyDrive2 and how you can use service account credentials to access google sheets.
PyDrive2 docs do not provide enough documentation on how to use service account credentials. I had to dig up its implementation to identify how to do that. To make it simpler for you, here’s the code to do that.
Create a new service account https://cloud.google.com/iam/docs/creating-managing-service-accounts
No need to give any permissions to the account.
Create and JSON Key https://cloud.google.com/iam/docs/creating-managing-service-account-keys
Create the sheet on google sheets and give Editor rights to the service account email which might look like xxxxxxx@xxxxxxx.iam.gserviceaccount.com
You can find this in the JSON key you downloaded in client_email property
credential_path = "credentials.json" # ensure the path is correct.
sheet_url = "https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # replace with the sheet url
worksheet_name = "Sheet1" # Name of the worksheet you want to access
gc = gspread.service_account(pkg_resources.resource_filename(__name__, credential_path))
sh = gc.open_by_url(sheet_url)
worksheet = sh.worksheet(worksheet_name)
records = worksheet.get_all_records()
df = pd.DataFrame(records)
# Now you can use df to do your operations.
That’s all you need to do.