Search code examples
pythongoogle-cloud-storage

How to move files in Google Cloud Storage from one bucket to another bucket by Python


Are there any API function that allow us to move files in Google Cloud Storage from one bucket in another bucket?

The scenario is we want Python to move read files in A bucket to B bucket. I knew that gsutil could do that but not sure Python can support that or not.

Thanks.


Solution

  • Using the google-api-python-client, there is an example on the storage.objects.copy page. After you copy, you can delete the source with storage.objects.delete.

    destination_object_resource = {}
    req = client.objects().copy(
            sourceBucket=bucket1,
            sourceObject=old_object,
            destinationBucket=bucket2,
            destinationObject=new_object,
            body=destination_object_resource)
    resp = req.execute()
    print json.dumps(resp, indent=2)
    
    client.objects().delete(
            bucket=bucket1,
            object=old_object).execute()