我正在尝试使用 try/except 来处理 pygsheets 库的错误处理。我的代码如下:
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.')
当工作表不存在时,我想创建一个新工作表。但是,我收到错误“未定义 WorksheetNotFound”。我知道我没有在我的代码中的任何地方定义术语 WorksheetNotFound,但我的理解是'except'语句会捕获'WorksheetNotFound'类型的任何错误(这是我在尝试访问工作表时遇到的错误不存在)。try/except 是否不适用于所有错误?还是只有某些类型的错误可以被 except 语句识别?谢谢!