This topic describes how to delete objects.

Warning Deleted objects cannot be restored. Exercise caution when you delete objects.

Delete a single object

The following code provides an example on how to delete a single object:

# -*- coding: utf-8 -*-
import oss2

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS, because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine operations and maintenance. To create a RAM user, log on to https://ram.console.aliyun.com.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint based on your requirements.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')

# Delete an object. <yourObjectName> indicates the full path of the object that you want to delete and must include the file extension of the object. Example: abc/efg/123.jpg.
# To delete a folder, set <yourObjectName> to the corresponding folder name. If the folder is not empty, you must delete all objects in the folder before deleting the folder.
bucket.delete_object('<yourObjectName>')
			

Delete multiple objects

The following code provides an example on how to delete multiple objects at a time:

# Delete three objects at a time. A maximum of 1,000 objects can be deleted at a time.
result = bucket.batch_delete_objects(['<yourObjectName-a>', '<yourObjectName-b>', '<yourObjectName-c>'])
# Print the names of deleted objects.
print('\n'.join(result.deleted_keys))
			

Delete objects with a specified prefix

The following code provides an example on how to delete objects whose names contain a specified prefix:

# -*- coding: utf-8 -*-
import oss2

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS, because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine operations and maintenance. To create a RAM user, log on to https://ram.console.aliyun.com.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint based on your requirements.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
prefix = "<yourKeyPrefix>"

# List all objects with a specified prefix.
for obj in oss2.ObjectIterator(bucket, prefix=prefix):
    bucket.delete_object(obj.key)