All Products
Search
Document Center

Object Storage Service:Delete Objects (Python SDK V1)

Last Updated:Mar 01, 2026

You can delete a single object, multiple specified objects, objects whose names contain a specific prefix, or an entire folder and all objects within it.

Warning

Deleted objects cannot be recovered. Exercise caution when you delete objects.

Prerequisites

  • Credentials: Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. For details, see Configure access credentials.

  • Permissions: You must have the oss:DeleteObject permission. For details, see Attach a custom policy to a RAM user.

  • Client initialization: The examples in this topic create an oss2.Bucket instance by using an OSS endpoint. If you want to create an instance by using custom domain names or Security Token Service (STS), see Initialization.

  • Endpoint configuration: The examples in this topic use the public endpoint of the China (Hangzhou) region. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

Delete a single object

Call bucket.delete_object() to delete one object from a bucket. Specify the full path of the object, which does not include the bucket name.

To delete a folder, set the object name to the folder name. The folder must be empty before you can delete it.

The following example deletes an object named exampledir/exampleobject.txt from a bucket named examplebucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider


def delete_single_object():
    """Delete a single object from an OSS bucket."""
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

    # Specify the full path of the object. Do not include the bucket name.
    try:
        bucket.delete_object('exampledir/exampleobject.txt')
        print("Object deleted successfully.")
    except oss2.exceptions.OssError as e:
        print(f"Failed to delete object: {e}")


if __name__ == '__main__':
    delete_single_object()

Batch delete objects

You can manually delete up to 1,000 objects in a single request. You can delete objects by specifying their names, by matching a prefix, or by targeting a folder and all objects within it.

You can also configure lifecycle rules to automatically delete objects. For more information, see Lifecycle rules based on the last modified time.

Delete objects by name

Call bucket.batch_delete_objects() with a list of object keys to delete up to 1,000 objects in one request. The method returns a result object whose deleted_keys attribute contains the names of the successfully deleted objects.

The following example deletes three objects from a bucket named examplebucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider


def batch_delete_by_name():
    """Delete multiple objects by specifying their names."""
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

    # Specify the full path of each object. Do not include the bucket name.
    keys_to_delete = ['exampleobject1.jpg', 'testobject2.png', 'destobject3.txt']

    try:
        result = bucket.batch_delete_objects(keys_to_delete)
        print("Deleted objects:")
        print('\n'.join(result.deleted_keys))
    except oss2.exceptions.OssError as e:
        print(f"Batch delete failed: {e}")


if __name__ == '__main__':
    batch_delete_by_name()

Delete objects by prefix or folder

Use oss2.ObjectIterator to list objects that match a specific prefix, then delete each object individually with bucket.delete_object().

Warning

If the prefix is not specified or is set to NULL, all objects in the bucket are deleted. Exercise caution when you specify a prefix in a delete operation.

Prefix behavior:

Prefix valueEffect
'src'Deletes all objects whose names start with src, including the src folder and all objects within it, as well as any non-folder objects that share the prefix (for example, srcbackup.txt).
'src/'Deletes only the src folder and all objects within it.

The following example deletes all objects whose names match a given prefix from a bucket named examplebucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider


def delete_by_prefix(prefix):
    """Delete all objects whose names match the specified prefix.

    Args:
        prefix: The prefix to match. For example, 'src' matches all objects
                whose names start with 'src'. Use 'src/' to match only the
                'src' folder and its contents.
    """
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

    # Iterate over all objects that match the prefix and delete each one.
    deleted_count = 0
    for obj in oss2.ObjectIterator(bucket, prefix=prefix):
        try:
            bucket.delete_object(obj.key)
            deleted_count += 1
        except oss2.exceptions.OssError as e:
            print(f"Failed to delete {obj.key}: {e}")

    print(f"Deleted {deleted_count} objects with prefix '{prefix}'.")


if __name__ == '__main__':
    # Delete all objects whose names start with 'src'.
    delete_by_prefix('src')

    # To delete only the 'src' folder and its contents, use:
    # delete_by_prefix('src/')

Best practices

  • Enable versioning before deleting objects. With versioning enabled, deleted objects can be recovered. For more information, see Versioning.

  • Use lifecycle rules for bulk cleanup. Rather than manually deleting large numbers of objects, configure lifecycle rules to automatically remove objects based on their last modified time. For more information, see Lifecycle rules based on the last modified time.

  • Always validate the prefix before prefix-based deletion. Double-check that your prefix value is correct and non-empty. An empty prefix matches every object in the bucket, which results in complete data loss.

  • Handle errors in production code. Wrap delete operations in try/except blocks to catch oss2.exceptions.OssError. For batch deletes using batch_delete_objects(), inspect result.deleted_keys to confirm which objects were successfully deleted.

  • Verify folder contents before deleting a folder. To delete a folder with delete_object(), the folder must be empty. Delete all objects inside the folder first, then delete the folder itself.

References

  • For the complete sample code that shows how to delete objects, see GitHub examples.

  • For more information about the API operation used to delete a single object, see DeleteObject.

  • For more information about the API operation used to delete multiple objects, see DeleteMultipleObjects.