Copying contents from one folder to another in same GCS Bucket

Viewed 378

I have a Python script that does some processing files on the input folder on my GCS Bucket. After processing completes, I want to move these files to another folder in the same GCS Bucket. Any idea how it can be implemented.

1 Answers

There is no such thing as "folders" in cloud storage buckets. You just need to copy the blob file to a new destination file name, and delete the former one, as follows :

import logging
from google.cloud import storage

STORAGE_BUCKET=""

def move_image_within_bucket(source_blob_name: str, origin_folder: str, destination_folder: str):
   """ Move image file from one folder to another folder within same Storage bucket """
   storage_client = storage.Client()
   bucket = storage_client.bucket(STORAGE_BUCKET)
   source_blob = bucket.get_blob(source_blob_name)
   destination_blob_name = source_blob_name.replace(origin_folder, destination_folder, 1)
   blob_copy = bucket.copy_blob(source_blob, bucket, new_name=destination_blob_name)
   logging.info(f"Image {source_blob} moved from folder {origin_folder} to {destination_folder} within bucket {STORAGE_BUCKET}")
   source_blob.delete()

   # example : move_image_within_bucket(source_blob_name="dev/image.jpg", origin_folder="dev", destination_folder="prod")
Related