|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2025 Google LLC |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the 'License'); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +import sys |
| 18 | + |
| 19 | +# [START storage_move_object] |
| 20 | +from google.cloud import storage |
| 21 | + |
| 22 | + |
| 23 | +def move_object(bucket_name: str, blob_name: str, new_blob_name: str) -> None: |
| 24 | + """Moves a blob to a new name within the same bucket using the move API.""" |
| 25 | + # The name of your GCS bucket |
| 26 | + # bucket_name = "your-bucket-name" |
| 27 | + |
| 28 | + # The name of your GCS object to move |
| 29 | + # blob_name = "your-file-name" |
| 30 | + |
| 31 | + # The new name of the GCS object |
| 32 | + # new_blob_name = "new-file-name" |
| 33 | + |
| 34 | + storage_client = storage.Client() |
| 35 | + |
| 36 | + bucket = storage_client.bucket(bucket_name) |
| 37 | + blob_to_move = bucket.blob(blob_name) |
| 38 | + |
| 39 | + # Use move_blob to perform an efficient, server-side move. |
| 40 | + moved_blob = bucket.move_blob( |
| 41 | + blob=blob_to_move, new_name=new_blob_name |
| 42 | + ) |
| 43 | + |
| 44 | + print(f"Blob {blob_to_move.name} has been moved to {moved_blob.name}.") |
| 45 | + |
| 46 | + |
| 47 | +# [END storage_move_object] |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + move_object( |
| 51 | + bucket_name=sys.argv[1], |
| 52 | + blob_name=sys.argv[2], |
| 53 | + new_blob_name=sys.argv[3], |
| 54 | + ) |
0 commit comments