You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取Google Bucket的xlsx文件时无文件触发自定义报错如何实现?

实现方案

提供两种可直接使用的实现方式,均不会抛出系统原生报错,目标文件不存在时会自动调用function1打印提示:

方案1:提前检查文件是否存在(推荐,性能更好)

调用GCS官方exists()方法先校验目标文件是否存在,不存在直接触发提示逻辑,不执行后续读取操作:

import pandas as pd
from google.cloud import storage

def function1():
     print("no file in the folder")

def main(target_folder: str = "folder_name_2"):
    storage_client = storage.Client.from_service_account_json(
        Constants.GCP_CRENDENTIALS)
    bucket = storage_client.bucket(Constants.GCP_BUCKET_NAME)
    blob_path = f"{target_folder}/{Constants.GCP_FILE_NAME}"
    blob = bucket.blob(blob_path)
    
    # 新增文件存在性判断
    if not blob.exists():
        function1()
        return
    
    # 文件存在时执行读取逻辑
    data_bytes = blob.download_as_bytes()
    df = pd.read_excel(data_bytes, engine='openpyxl')
    print(df)

如果需要遍历所有文件夹查找目标文件,可参考如下循环判断逻辑:

import pandas as pd
from google.cloud import storage

# 列出所有需要检查的文件夹
FOLDERS_TO_CHECK = ["folder_name_1", "folder_name_2", "folder_name_3"]

def function1():
     print("no file in the folder")

def main():
    storage_client = storage.Client.from_service_account_json(
        Constants.GCP_CRENDENTIALS)
    bucket = storage_client.bucket(Constants.GCP_BUCKET_NAME)
    file_found = False
    
    for folder in FOLDERS_TO_CHECK:
        blob_path = f"{folder}/{Constants.GCP_FILE_NAME}"
        blob = bucket.blob(blob_path)
        if blob.exists():
            data_bytes = blob.download_as_bytes()
            df = pd.read_excel(data_bytes, engine='openpyxl')
            print(df)
            file_found = True
            break
    
    # 所有文件夹均未找到目标文件时触发提示
    if not file_found:
        function1()

方案2:异常捕获(兼容更多异常场景)

如果需要同时处理网络波动、权限不足等其他可能导致读取失败的异常,可通过try-except块捕获异常统一触发提示:

import pandas as pd
from google.cloud import storage
from google.cloud.exceptions import NotFound

def function1():
     print("no file in the folder")

def main(target_folder: str = "folder_name_2"):
    storage_client = storage.Client.from_service_account_json(
        Constants.GCP_CRENDENTIALS)
    bucket = storage_client.bucket(Constants.GCP_BUCKET_NAME)
    blob_path = f"{target_folder}/{Constants.GCP_FILE_NAME}"
    blob = bucket.blob(blob_path)
    
    try:
        data_bytes = blob.download_as_bytes()
        df = pd.read_excel(data_bytes, engine='openpyxl')
        print(df)
    except (NotFound, Exception):
        # 找不到文件或其他读取异常均触发提示
        function1()

内容的提问来源于stack exchange,提问作者aristotle29

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:15:09