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
Solution 1:
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.
Solution 2:
In case if you want to rename an existing file in the bucket.
defrename_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
Post a Comment for "How To Rename A File While Storing It To A Gcs Bucket"