代码之家  ›  专栏  ›  技术社区  ›  kee

Google云存储:如何在Python中(递归地)删除文件夹

  •  4
  • kee  · 技术社区  · 6 年前

    我测试了这个代码:

    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/')
    

    1 回复  |  直到 6 年前
        1
  •  24
  •   jterrace    6 年前

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

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

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