javalearner
javalearner

Reputation: 377

How to rename a file while storing it to a GCS bucket

I am reading a file from one of directory.post validations I need to upload a file with appending timestamp to it.

How do I rename the file while uploading it to a GCS bucket?

I am using the Google Storage client. I see that for S3 the boto client has a method where we can pass a upload_name= parameter but I don't see a similar one in GCS.

Upvotes: 1

Views: 4522

Answers (2)

adam shamsudeen
adam shamsudeen

Reputation: 1882

In case if you want to rename an existing file in the bucket.

def rename_blob(bucket_name, blob_name, new_blob_name):
    """
    Function for renaming file in a bucket buckets.

    inputs
    -----
    bucket_name: name of bucket
    blob_name: str, name of file 
        ex. 'data/some_location/file_name'
    new_blob_name: str, name of file in new directory in target bucket 
        ex. 'data/destination/file_name'
    """
    storage_client = storage.Client.from_service_account_json('creds.json')

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)
    new_blob = bucket.rename_blob(blob, new_blob_name)
    return new_blob.public_url

Upvotes: 4

Kunal Deo
Kunal Deo

Reputation: 2298

You could use rename_blob to achieve the same result.

from google.cloud import storage

storage_client = storage.Client() 
bucket = storage_client.get_bucket("mybucket")
blob = bucket.blob("myfile")
blob.upload_from_filename("mynewfile")
bucket.rename_blob(blob, "mynewfile")

Another alternative is using the rest API where you can just pass the name parameter.

Upvotes: 3

Related Questions