Reputation: 1057
Using pygsheets, I was looking around for a good way to open a Google sheet (by title) if it already exists, otherwise create it.
At the same time, I also wanted to make it r/w to myself and r/o to the rest of the world upon creating it.
Upvotes: 1
Views: 1914
Reputation: 1057
Here's something that does just that:
import pygsheets
creds_file = "/path/to/your_creds_file.json"
gc = pygsheets.authorize(service_file=creds_file)
sheet_title = "my_google_sheet"
# Try to open the Google sheet based on its title and if it fails, create it
try:
sheet = gc.open(sheet_title)
print(f"Opened spreadsheet with id:{sheet.id} and url:{sheet.url}")
except pygsheets.SpreadsheetNotFound as error:
# Can't find it and so create it
res = gc.sheet.create(sheet_title)
sheet_id = res['spreadsheetId']
sheet = gc.open_by_key(sheet_id)
print(f"Created spreadsheet with id:{sheet.id} and url:{sheet.url}")
# Share with self to allow to write to it
sheet.share('[email protected]', role='writer', type='user')
# Share to all for reading
sheet.share('', role='reader', type='anyone')
# Write something into it
wks = sheet.sheet1
wks.update_value('A1', "something")
Upvotes: 1