Skip to content

Instantly share code, notes, and snippets.

@isaiahnixon
Created September 23, 2021 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaiahnixon/69719181a4d86612a5db8329229811a0 to your computer and use it in GitHub Desktop.
Save isaiahnixon/69719181a4d86612a5db8329229811a0 to your computer and use it in GitHub Desktop.
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