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

Python操作Google Cloud Storage遇AttributeError错误求助

解决Google Cloud Storage操作中的AttributeError错误

错误原因

报错AttributeError: 'str' object has no attribute 'write'的核心问题是:
google.cloud.storage.Blob.download_to_file()方法要求传入可写的文件流对象,但你传入的是字符串格式的文件路径("/tmp/plant_disease.h5"),字符串类型没有write方法,导致调用失败。

修复方案

有两种简单的修复方式:

方式1:打开文件流后传入download_to_file

修改download_blob函数,通过open()创建二进制写入模式的文件流,再传递给方法:

def download_blob(bucket_name, source_blob_name, destination_file_name):
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    with open(destination_file_name, "wb") as f:
        blob.download_to_file(f)
    print(f"Blob {source_blob_name} downloaded to {destination_file_name}.")

方式2:使用更适合的download_to_filename方法

Google Cloud Storage提供了直接接受文件路径的download_to_filename()方法,内部会自动处理文件流,代码更简洁:

def download_blob(bucket_name, source_blob_name, destination_file_name):
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)
    print(f"Blob {source_blob_name} downloaded to {destination_file_name}.")

其他潜在问题修复

除了上述错误,代码中还有两个会导致500错误的问题:

  1. 变量名大小写不匹配:定义的类名列表是class_names(小写开头),但预测时误用了CLASS_NAMES,会触发NameError,需统一为:
predicted_class = class_names[np.argmax(predictions_array[0])]
  1. 预测结果引用错误:原代码中predictions被赋值为类名字符串后,又用predictions[0]计算置信度,会触发TypeError,需先保存原始预测数组:
# 修改预测逻辑
predictions_array = model.predict(img_array)
predicted_class = class_names[np.argmax(predictions_array[0])]
confidence = round(100 * np.max(predictions_array[0]), 2)

return {
    "class": predicted_class,
    "confidence": confidence
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 06:57:05