如何从Python删除GCS文件夹?

时间:2018-11-06 03:09:39

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

使用https://github.com/googleapis/google-cloud-python/tree/master/storagehttps://github.com/GoogleCloudPlatform/appengine-gcs-client,我可以通过指定文件名来删除文件,但是似乎没有删除文件夹的方法。

有什么方法可以删除文件夹吗?

我在stackvoerflow中发现了这个(Google Cloud Storage: How to Delete a folder (recursively) in Python),但是这个答案只是删除了文件夹中的所有文件,而不是删除了文件夹本身。

2 个答案:

答案 0 :(得分:3)

您引用的anwser中提到的代码有效,前缀应如下所示:

from google.cloud import storage

storage_client = storage.Client()
bucket = storage_client.get_bucket('my-bucket')

blobs = bucket.list_blobs(prefix='my-folder/')

for blob in blobs:
    blob.delete()

答案 1 :(得分:1)

from google.cloud import storage

def deleteStorageFolder(bucketName, folder):
    """
    This function deletes from GCP Storage

    :param bucketName: The bucket name in which the file is to be placed
    :param folder: Folder name to be deleted
    :return: returns nothing
    """
    cloudStorageClient = storage.Client()
    bucket = cloudStorageClient.bucket(bucketName)
    try:
        bucket.delete_blobs(blobs=bucket.list_blobs(prefix=folder))
    except Exception as e:
        print str(e.message)