Accessing google sheet from python
In this article, we will be accessing google sheet from python code.
Firstly, create service account by following:
- Go to https://console.developers.google.com/ and create new or select existing project


Also enable Google Drive Api following the same above steps.
Creating service account credentials
-
Go to Credentials, Create Credentials
Untitled -
Choose Service Account:
Untitled -
Give service account name, and description. You can skip all other optional things.
Untitled -
Press “Manage service accounts” above Service Accounts.
-
Press on ⋮ near recently created service account and select “Manage keys” and then click on “ADD KEY > Create new key”.

- Select JSON key type and press “Create”.

This will automatically downloads the json key file to your computer.
Now, move to your working directory.
#Create virtual-env:
python -m venv googlesheets-env
#Activate the virtual env
source googlesheets-env/bin/activate
# install gspread package
pip install gspread
# Now we are ready to go.
Awww, before moving ahead, Go to https://docs.google.com/spreadsheets/u/0/ and create new spreadsheets.
Give it a name, python-script.
Open downloaded json file, it has client_email entry. Share the created spreadsheet with the client_email in the downloaded json, as shown.


Bangg, now write Hello world on cell A1.

let’s Access this cell content from python. Write below code as hello.py:
import gspread
gc = gspread.service_account(filename="path/to/downloaded/json/service_account.json")
sh = gc.open("python-script")
print(sh.sheet1.get('A1'))
run it as python hello.py
This will output as:

This way, we can access our sheets from python code and do some tasks automatically.
We will be doing some more cool stuffs. Stay connected.