简体   繁体   中英

Copying contents from one folder to another in same GCS Bucket

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM