未定义名称“WorksheetNotFound”

2024-10-01 02:33:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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,但我的理解是'Exception'语句将捕获'WorksheetNotFound'类型的任何错误(这是我在尝试访问不存在的工作表时遇到的错误)。try/except是否不能处理所有错误?或者except语句只识别某些类型的错误?谢谢


Tags: columns代码dfforindexvalue错误col