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.")
1

There are 1 best solutions below

4
Julia On

Your error "AttributeError: 'Blob' object doesn't have the 'copy_to' attribute." suggests that the copy_to method isn't available for the Blob object you're using from the Google Cloud Storage library version you have. The copy_to method isn't a regular feature for the Blob class in Google Cloud Storage.

To copy a file from one storage bucket to another, you should use the copy_blob method provided by the Bucket class. Here's how you can adjust your code to make it work:

    source_blob = source_bucket.blob(filename)
    destination_blob = destination_bucket.blob(target_path + filename)

    new_blob = source_bucket.copy_blob(source_blob, destination_bucket, destination_blob)
    source_blob.delete()

    print(f"The file {filename} has been successfully transferred.")

In this piece of code, the copy_blob method 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: