I am trying to transfer a file from one bucket to another bucket using Python code in Google Cloud Function but I am getting this error "AttributeError: 'Blob' object has no attribute 'copy_to'". These are some additional details about the process. source_bucket : gcf-v2-uploads-632430838198-us-east1 target_bucket : ca-app-corp-finance-dev-444 target_path : gs://ca-app-corp-finance-dev-444/process/fin_essbase/data/incoming/essbase/ filename : key.ppk
I tried below code
from google.cloud import storage
def transfer_file(data, context):
source_bucket_name = "gcf-v2-uploads-632430838198-us-east1"
destination_bucket_name = "ca-app-corp-finance-dev-444"
target_path = "process/fin_essbase/data/incoming/essbase/"
filename = "key.ppk"
storage_client = storage.Client()
source_bucket = storage_client.bucket(source_bucket_name)
destination_bucket = storage_client.bucket(destination_bucket_name)
source_blob = source_bucket.blob(filename)
destination_blob = destination_bucket.blob(target_path + filename)
source_blob.copy_to(destination_blob)
source_blob.delete()
print(f"File {filename} transferred successfully.")
Your error "AttributeError: 'Blob' object doesn't have the 'copy_to' attribute." suggests that the
copy_tomethod isn't available for theBlobobject you're using from the Google Cloud Storage library version you have. Thecopy_tomethod isn't a regular feature for theBlobclass in Google Cloud Storage.To copy a file from one storage bucket to another, you should use the
copy_blobmethod provided by theBucketclass. Here's how you can adjust your code to make it work:In this piece of code, the
copy_blobmethod from the source bucket is used to copy the file to the destination bucket. After that, the original file is removed from the source bucket.For more information, you can check these references:
Copying an object between buckets:
Moving files in Google Cloud Storage between buckets using Python