【问题标题】:Google Cloud Storage: How to Delete a folder (recursively) in PythonGoogle Cloud Storage:如何在 Python 中(递归)删除文件夹
【发布时间】:2018-10-13 05:05:48
【问题描述】:

我正在尝试使用其 Python 库删除 GCS 中的一个文件夹及其所有内容(包括子目录)。另外我知道 GCS 并没有真正的文件夹(但前缀?),但我想知道我该怎么做?

我测试了这段代码:

from google.cloud import storage

def delete_blob(bucket_name, blob_name):
    """Deletes a blob from the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(blob_name)

    blob.delete()

delete_blob('mybucket', 'top_folder/sub_folder/test.txt')
delete_blob('mybucket', 'top_folder/sub_folder/')

第一次调用 delete_blob 有效,但第二次无效。我可以递归删除文件夹吗?

【问题讨论】:

    标签: google-cloud-storage google-cloud-python


    【解决方案1】:

    要删除以某个前缀开头的所有内容(例如,目录名称),您可以遍历列表:

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blobs = bucket.list_blobs(prefix='some/directory')
    for blob in blobs:
      blob.delete()
    

    请注意,对于包含数百万或数十亿对象的非常大的存储桶,这可能不是一个很快的过程。为此,您需要做一些更复杂的事情,例如在多个线程中删除或使用生命周期配置规则来安排要删除的对象。

    【讨论】:

    • 我最初的预感是列出所有,然后迭代并删除与给定路径匹配的那些.. 但很高兴知道 API 中存在此选项(在我的情况下为 java-storage API)..谢谢你:)
    • 您也可以使用bucket.delete_blobs 方法删除所有列表文件,其中一次网络往返O(1) 而不是O(n) 单独的delete 调用。
    • bucket.delete_blobs 一一删除。 googleapis.dev/python/storage/latest/…@user482594
    【解决方案2】:

    现在可以通过以下方式完成:

    def delete_folder(cls, bucket_name, folder_name):
        bucket = cls.storage_client.get_bucket(bucket_name)
        """Delete object under folder"""
        blobs = list(bucket.list_blobs(prefix=folder_name))
        bucket.delete_blobs(blobs)
        print(f"Folder {folder_name} deleted.")
    

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      相关资源
      最近更新 更多