我正在尝试设置云函数,以便在GCP的一个存储桶内的文件夹之间移动文件。
每当用户将文件加载到提供的bucket文件夹中时,我的云函数就会将文件移动到大数据脚本所在的另一个文件夹中。
它在设置时显示成功,但是文件没有从源文件夹中移动。
感谢您的帮助
from google.cloud import storage
def move_file(bucket_name, bucket_Folder, blob_name):
"""Moves a blob from one folder to another with the same name."""
bucket_name = 'bucketname'
blob_name = 'filename'
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
source_blob = bucket.blob("Folder1/" + blob_name)
new_blob = bucket.copy_blob(source_blob, bucket, "Folder2/" + blob_name)
blob.delete()
print('Blob {} in bucket {} copied to blob {} .'.format(source_blob.name, bucket.name, new_blob.name))
发布于 2020-01-07 21:58:24
在您提供的代码中,没有在任何地方定义变量blob
,因此源文件不会被删除。将该行更改为source_blob.delete()
,而不是blob.delete()
。
另外,我假设你已经意识到你只是在"moving"一个文件。如果您想要将所有以Folder1/
为前缀的文件移动到Folder2
,您可以执行以下操作:
from google.cloud import storage
def move_files(self):
storage_client = storage.Client()
bucket = storage_client.get_bucket('bucketname')
blobs = bucket.list_blobs(prefix='Folder1/')
for blob in blobs:
bucket.rename_blob(blob, new_name=blob.name.replace('Folder1/', 'Folder2/'))
对于后者,我认为可以有更有效或更好的方法来做到这一点。
发布于 2020-01-07 21:56:07
如果您只是在同一存储桶内移动对象,则可以使用所需的路由进行rename the object。
在Google Cloud Platform Storage中,没有文件夹,只有文件夹的假象。存储桶名称之后的所有内容都是对象名称的一部分。
另外,我可以在您的函数中看到许多错误。您可以使用此通用函数将blob从一个文件夹移动到同一存储桶内的另一个文件夹:
从google.cloud导入存储定义rename_blob( bucket_name,blob_name,new_name):“重命名blob。”#bucket_name=“您的存储桶名称”# blob_name =“文件夹/myobject”# new_name = "newfolder/myobject“
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)
new_blob = bucket.rename_blob(blob, new_name)
print("Blob {} has been renamed to {}".format(blob.name, new_blob.name))
https://stackoverflow.com/questions/59635453
复制相似问题