Home > Software engineering >  Python gspread create sheet if not exist
Python gspread create sheet if not exist

Time:09-21

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")

CodePudding user response:

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 NWorksheetNotFound:
    wks = mySheet.add_worksheet("BOT: output","999","20")

CodePudding user response:

What about using os.path.exists to check if the file is already existing? If it doesn't exists you create the file, otherwise you do nothing.

import os    
if not os.path.exists('path/to/BOT: output'):
    mySheet.worksheet("BOT: output")
  • Related