Python跨GCP存储桶移动文件报404 NotFound错误求助
报错原因
报错的核心是对GCS(Google Cloud Storage)的路径规则理解错误:
- GCS本身不存在实体文件夹,所有路径层级都是对象(blob)名称的前缀部分,bucket名称是全局唯一的,不允许包含斜杠
/ - 代码中将
"BUCKET_2/folder"作为目标bucket名称传入SDK,SDK会直接将该字符串作为bucket名发起API请求,GCS找不到名为BUCKET_2/folder的bucket,因此返回404 Not Found错误。 - 额外逻辑问题:原有
move_blob函数仅执行了复制操作,未删除源bucket中的原文件,实际是复制逻辑而非移动逻辑。
修复方案
- 将目标bucket名称修正为纯bucket名
"BUCKET_2",把目标路径前缀folder/拼接到目标blob的名称前 - 在复制完成后删除源blob,实现真正的文件移动效果
- 增加CSV文件过滤逻辑,仅移动指定后缀的文件,避免误传其他类型文件
修复后的完整代码如下:
from google.cloud import storage def move_blob(bucket_name, blob_name, destination_bucket_name, destination_blob_name): """Moves a blob from one bucket to another with a new name.""" storage_client = storage.Client() source_bucket = storage_client.bucket(bucket_name) source_blob = source_bucket.blob(blob_name) destination_bucket = storage_client.bucket(destination_bucket_name) blob_copy = source_bucket.copy_blob( source_blob, destination_bucket, destination_blob_name ) # 复制完成后删除源文件,完成移动操作 source_blob.delete() print( "Blob {} in bucket {} moved to blob {} in bucket {}.".format( source_blob.name, source_bucket.name, blob_copy.name, destination_bucket.name, ) ) def list_blobs(): """Lists all the blobs in the bucket.""" bucket_name = "BUCKET_1" destination_bucket_name = "BUCKET_2" # 目标路径前缀单独定义,拼接到blob名前 target_prefix = "folder/" storage_client = storage.Client() blobs = storage_client.list_blobs(bucket_name) for blob in blobs: # 仅移动CSV文件,不需要可删除该判断 if not blob.name.endswith('.csv'): continue print(blob.name) blob_name = blob.name # 拼接目标路径 destination_blob_name = f"{target_prefix}{blob_name}" move_blob(bucket_name, blob_name, destination_bucket_name, destination_blob_name) list_blobs()
权限说明
运行代码前请确保当前使用的认证身份(服务账号/用户账号)持有以下权限:
- 源bucket:
storage.objects.list、storage.objects.get、storage.objects.delete - 目标bucket:
storage.objects.create
内容的提问来源于stack exchange,提问作者Renan Saia
相关产品推荐
相关产品推荐

