ibm-cloud-docs / cloud-object-storage

cloud-object-storage
15 stars 46 forks source link

Python code for deleting files in buckets does not work #138

Closed sean-nellington closed 1 year ago

sean-nellington commented 2 years ago

Python code for deleting files in buckets does not work. I had to re-write the code. The version I created (below) deletes all files from all buckets, so I don't recommend copying and pasting it directly, but it does work.


    print("Retrieving bucket contents from: {0}".format(bucket_name))
    returnArray = []
    try:
        files = cos.Bucket(bucket_name).objects.all()
        for file in files:
            print("Item: {0} ({1} bytes).".format(file.key, file.size))
            returnArray.append(file.key)
    except Exception as e:
        print("Unable to retrieve bucket contents: {0}".format(e))

    return returnArray

def delete_item(bucket_name, item_name):
    print("Deleting item: {0}".format(item_name))
    try:
        cos.Object(bucket_name.name, item_name).delete()
        print("Item: {0} deleted!".format(item_name))
    except Exception as e:
        print("Unable to delete item: {0}".format(e))

def main():
    for bucket in cos.buckets.all():
        deleteListArray = get_bucket_contents(bucket.name, 1000)
        if len(deleteListArray) == 0:
            print("Empty bucket")
        for item_name in deleteListArray:
            delete_item(bucket, item_name)

main()