Search code examples
pythongoogle-sheetsjupyter-notebooktry-catchgspread

Python gspread create sheet if not exist


I am trying to create a new sheet called "BOT: output". However, if I run the code once it works fine, but when I run the code again and that sheet exist it gives me an error. I tried to create an if condition to see if the sheet exist just identify it as wks2, but this will give an error if the sheet itsn't there in the first place.

 try:
     wks2 = mySheet.worksheet("BOT: output")
 except notFound:
     wks2 = mySheet.add_worksheet("BOT: output","999","20")

Solution

  • your issue is located at the exception you catch. It's not the right one.

    According to gspread documentation it raises the WorksheetNotFound exception of it does not exists.

    So your code should look like this (with simplifications)

    try:
        wks = mySheet.worksheet("BOT: output")
    except gspread.exceptions.WorksheetNotFound:
        wks = mySheet.add_worksheet("BOT: output","999","20")