如何从 Python 中删除 GCS 文件夹?

Tai*_*chi 5 python 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),但是这个答案只是删除了文件夹中的所有文件,而不是删除了文件夹本身。

dha*_*man 12

您引用的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()
Run Code Online (Sandbox Code Playgroud)


小智 6

from google.cloud import storage
    
def delete_storage_folder(bucket_name, folder):
    """
    This function deletes from GCP Storage

    :param bucket_name: The bucket name in which the file is to be placed
    :param folder: Folder name to be deleted
    :return: returns nothing
    """
    cloud_storage_client = storage.Client()
    bucket = cloud_storage_client.bucket(bucket_name)
    try:
        bucket.delete_blobs(blobs=list(bucket.list_blobs(prefix=folder)))
    except Exception as e:
        print(str(e.message))
Run Code Online (Sandbox Code Playgroud)