I'm trying to use try/except for error handling working with the pygsheets library. My code is as follows:
def export_col_values(workbook, df, columns):
"""for a list of columns, creates a new sheet for each column and exports unique values and their counts to that sheet"""
for col in columns:
value_counts = df[col].value_counts()
counts_df = pd.DataFrame(value_counts).reset_index()
counts_df['index'] = counts_df['index'].astype(str)
try:
worksheet = workbook.worksheet_by_title(col)
except WorksheetNotFound:
workbook.add_worksheet(col)
worksheet = workbook.worksheet_by_title(col)
worksheet.set_dataframe(counts_df, start='A1')
print(f'{len(columns)} sets of column values exported.')
when the worksheet does not exist, i want to create a new worksheet. however, i get the error 'WorksheetNotFound' is not defined. i understand that I haven't defined the term WorksheetNotFound anywhere in my code, but my understanding was that the 'except' statement would catch any error of the 'WorksheetNotFound' type (this is the error I get when trying to access a worksheet that does not exist). Does try/except not work with all errors? Or are there only certain types of errors that an except statement recognizes? Thanks!