Home > Enterprise >  Python gspread delete sheet if exist
Python gspread delete sheet if exist

Time:09-20

I am automatically generating a new sheet called "BOT: output". However, if I run the code again and that sheet exist it gives me an error. I tried to create if condition to see if the sheet exist just identify it as wks2, but this will give an error if it doesn't exist in the first place its like an unending loop.

try:
    
    mySheet.worksheet("BOT: output")

except NameError:
    exists = False
else:
    exists = True

if exists:
    wks2 = mySheet.worksheet("BOT: output")
else:
    wks2 = 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")

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