Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python CRUD Module for Google Sheets Data with Pandas
import gspread
import pandas as pd
from gspread_dataframe import set_with_dataframe
import os
current_dir = os.path.dirname(os.path.realpath(__file__))
service_account_file = current_dir + '/service_account.json'
google_credentials = gspread.service_account(service_account_file)
def get_sheet(sheet_key, sheet_id):
data = google_credentials.open_by_key(sheet_key).get_worksheet(sheet_id).get_all_values()
headers = data.pop(0)
return pd.DataFrame(data, columns=headers)
def set_sheet(sheet_key, sheet_id, df):
set_with_dataframe(google_credentials.open_by_key(sheet_key).get_worksheet(sheet_id), df)
def clear_sheet(sheet_key, sheet_id):
google_credentials.open_by_key(sheet_key).get_worksheet(sheet_id).clear()
def append_row_to_sheet(sheet_key, sheet_id, row):
df = get_sheet(sheet_key, sheet_id)
df.loc[len(df.index)] = [
*row
]
set_sheet(sheet_key, sheet_id, df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment