如何通过Python将Google云存储中的文件从一个存储桶移动到另一个存储桶

如何通过Python将Google云存储中的文件从一个存储桶移动到另一个存储桶,python,google-cloud-storage,Python,Google Cloud Storage,是否有API函数允许我们将Google云存储中的文件从一个存储桶移动到另一个存储桶 我们希望Python将读取的文件从一个bucket移动到另一个bucket。我知道gsutil可以做到这一点,但不确定Python是否能够支持这一点 谢谢。您可以使用[1]中记录的GCS客户端库函数读取一个存储桶并写入另一个存储桶,然后删除源文件 您甚至可以使用[2]中记录的GCS REST API 链接: [1] - [2] -使用,页面上有一个示例。复制后,可以使用删除源 destination\u obje

是否有API函数允许我们将Google云存储中的文件从一个存储桶移动到另一个存储桶

我们希望Python将读取的文件从一个bucket移动到另一个bucket。我知道gsutil可以做到这一点,但不确定Python是否能够支持这一点


谢谢。

您可以使用[1]中记录的GCS客户端库函数读取一个存储桶并写入另一个存储桶,然后删除源文件

您甚至可以使用[2]中记录的GCS REST API

链接:
[1] -
[2] -

使用,页面上有一个示例。复制后,可以使用删除源

destination\u object\u resource={}
req=client.objects().copy(
sourceBucket=bucket1,
sourceObject=旧对象,
目标桶=桶2,
destinationObject=新对象,
body=目的地\对象\资源)
resp=req.execute()
打印json.dumps(resp,indent=2)
client.objects().delete(
桶=桶1,
对象=旧对象)。执行()

在同一个bucket内的目录之间移动blob或将blob移动到不同的bucket时,我使用了一个函数

from google.cloud import storage
import os

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="path_to_your_creds.json"

def mv_blob(bucket_name, blob_name, new_bucket_name, new_blob_name):
"""
Function for moving files between directories or buckets. it will use GCP's copy 
function then delete the blob from the old location.

inputs
-----
bucket_name: name of bucket
blob_name: str, name of file 
    ex. 'data/some_location/file_name'
new_bucket_name: name of bucket (can be same as original if we're just moving around directories)
new_blob_name: str, name of file in new directory in target bucket 
    ex. 'data/destination/file_name'
"""
storage_client = storage.Client()
source_bucket = storage_client.get_bucket(bucket_name)
source_blob = source_bucket.blob(blob_name)
destination_bucket = storage_client.get_bucket(new_bucket_name)

# copy to new destination
new_blob = source_bucket.copy_blob(
    source_blob, destination_bucket, new_blob_name)
# delete in old destination
source_blob.delete()

print(f'File moved from {source_blob} to {new_blob_name}')

在Google Compute Engine中,您甚至可以从Python应用程序运行外部gsutil命令来移动文件。您使用的是哪种Python API?请注意,为#1编写的库是为与App Engine一起使用而设计的。如果你没有使用App Engine,链接#2是你最好的选择。你能告诉我你正在为上面的代码导入哪个软件包吗?@Mahdi:you import
from google.cloud import storage
。用于GCP存储的Python云客户端的文档可以在以下位置找到: