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

使用Python复制GCS存储桶文件时遇Unicode转换错误求助

GCS跨存储桶复制文件时"could not be converted to unicode"错误的解决方案

错误原因

你的代码中错误地将destination_blob_name创建为Blob对象,而copy_blob方法的第三个参数要求传入的是目标Blob的名称字符串(即文件在目标桶中的路径/文件名),不是Blob实例。这导致Google Cloud Storage SDK在尝试将Blob对象转换为Unicode字符串时失败,抛出ValueError。

错误代码行:

destination_blob_name=source_bucket.blob(str(destination_blob_name))

这里完全不需要调用source_bucket.blob(),直接使用目标文件名的字符串即可。

修正后的代码

from google.cloud import storage
from google.oauth2 import service_account

# 移除重复导入的storage模块
credentials = service_account.Credentials.from_service_account_file("FILE.json")
client = storage.Client(project='PROJECT', credentials=credentials)

# 若source_bucket等变量本身已是字符串类型,无需额外str()转换
source_bucket = client.bucket(source_bucket)
source_blob = source_bucket.blob(source_blob)
destination_bucket = client.bucket(destination_bucket)

# 直接传入目标Blob的名称字符串,示例:"target-dir/copied-file.txt"
destination_blob_name = "目标文件路径/文件名"

blob_copy = source_bucket.copy_blob(source_blob, destination_bucket, destination_blob_name)

关键说明

  • copy_blob方法的参数要求:
    1. 第一个参数:要复制的源Blob对象
    2. 第二个参数:目标存储桶对象
    3. 第三个参数:目标Blob的名称字符串(不是Blob对象)
  • 如果希望目标文件名与源文件一致,可直接复用源Blob的名称:
    blob_copy = source_bucket.copy_blob(source_blob, destination_bucket, source_blob.name)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 01:22:04