Todos los productos
Search
Centro de documentos

Object Storage Service:Eliminar archivos (Python SDK V1)

Última actualización: Sep 03, 2026

Este tema describe cómo eliminar uno o varios archivos (objetos), o archivos con un prefijo específico, de un bucket con control de versiones habilitado.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.

  • Para eliminar un objeto, debe contar con el permiso oss:DeleteObject. Para obtener más información, consulte Grant a custom policy.

Comportamiento de eliminación en un bucket con control de versiones

El comportamiento de eliminación es a continuación:

  • Sin versionId especificado (eliminación suave):

    Si realiza una operación de eliminación sin especificar un versionId, OSS inserta un marcador de eliminación para la versión actual del objeto en lugar de eliminarlo. Cuando posteriormente ejecuta una operación GetObject, OSS detecta el marcador de eliminación y devuelve un error 404 Not Found. La respuesta también incluye el encabezado x-oss-delete-marker = true y el número de versión del nuevo marcador de eliminación en el encabezado x-oss-version-id.

    Un valor true para x-oss-delete-marker indica que la versión correspondiente al x-oss-version-id devuelto es un marcador de eliminación.

  • Con versionId especificado (eliminación permanente):

    Si realiza una operación de eliminación y especifica un versionId, OSS elimina permanentemente esa versión del objeto según el parámetro versionId del objeto params. Para eliminar una versión con el ID "null", utilice el parámetro params y establezca params['versionId'] = "null". OSS interpreta la cadena "null" como el versionId "null" y elimina el objeto con dicho versionId.

Eliminar un solo archivo

A continuación ejemplos muestran cómo eliminar de forma permanente o suave un solo objeto.

  • Eliminación permanente

    A continuación código muestra cómo eliminar permanentemente un objeto al especificar su versionId:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
    region = "cn-hangzhou"
    
    # Set yourBucketName to the name of the bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    # Set yourObjectName to the full path of the object. Do not include the bucket name. Example: example/test.txt.
    object_name = 'yourObjectName'
    
    # Specify the versionId of the object. This can also be the versionId of a delete marker.
    params = dict()
    params['versionId'] = 'yourObjectVersionIdOrDeleteMarkerVersionId'
    
    # Delete the object or the object associated with the delete marker that has the specified versionId.
    result = bucket.delete_object(object_name, params=params)
    print("delete object name: ", object_name)
    # If the versionId of an object is specified, the returned delete_marker is None and the returned versionId is the versionId of the specified object.
    # If the versionId of a delete marker is specified, the returned delete_marker is True and the returned versionId is the versionId of the specified delete marker.
    if result.delete_marker:
        print("delete del-marker versionid: ",result.versionid)
    else:
        print("delete object versionid:", result.versionid)
  • Eliminación suave

    A continuación código muestra cómo eliminar suavemente un objeto sin especificar un versionId:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
    region = "cn-hangzhou"
    
    # Set yourBucketName to the name of the bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    # Set yourObjectName to the full path of the object. Do not include the bucket name. Example: example/test.txt.
    object_name = 'yourObjectName'
    
    # Soft delete the object without specifying a versionId. This operation adds a delete marker to the object.
    result = bucket.delete_object(object_name)
    # View the delete marker.
    print("delete marker: ", result.delete_marker)
    # View the versionId of the returned delete marker.
    print("delete marker versionid: ", result.versionid)

Eliminar varios archivos

A continuación ejemplos muestran cómo eliminar de forma permanente o suave varios objetos.

  • Eliminación permanente

    A continuación código muestra cómo eliminar permanentemente varios objetos y marcadores de eliminación al especificar sus versionIds:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    from oss2.models import BatchDeleteObjectVersion
    from oss2.models import BatchDeleteObjectVersionList
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
    region = "cn-hangzhou"
    
    # Set yourBucketName to the name of the bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    version_list = BatchDeleteObjectVersionList()
    # You can pass the versionId of an object or a delete marker.
    obj1_versionid = 'yourObject1VersionId'
    obj1_del_marker_versionid = 'yourObject1DelMarkerVersionId'
    obj2_versionid = 'yourObject2VersionId'
    obj2_del_marker_versionid = 'yourObject2DelMarkerVersionId'
    version_list.append(BatchDeleteObjectVersion(key='yourObject1Name', versionid=obj1_versionid))
    version_list.append(BatchDeleteObjectVersion(key='yourObject1Name', versionid=obj1_del_marker_versionid))
    version_list.append(BatchDeleteObjectVersion(key='yourObject2Name', versionid=obj2_versionid))
    version_list.append(BatchDeleteObjectVersion(key='yourObject2Name', versionid=obj2_del_marker_versionid))
    
    # Batch delete objects or delete markers with specified versionIds.
    result = bucket.delete_object_versions(version_list)
    # View the versionIds of the deleted objects or delete markers.
    for del_version in result.delete_versions:
        print('del object name:', del_version.key)
        # Check whether a delete marker was deleted.
        print('Is del marker:', del_version.delete_marker)
        # If a delete marker was deleted, print the versionId of the deleted delete marker. Otherwise, print the versionId of the deleted object.
        if del_version.delete_marker:
            print('del object del_marker.versionid', del_version.delete_marker_versionid)
        else:
            print('del object versionid:', del_version.versionid)
  • Eliminación suave

    A continuación código muestra cómo eliminar suavemente varios objetos sin especificar sus versionIds:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    from oss2.models import BatchDeleteObjectVersion
    from oss2.models import BatchDeleteObjectVersionList
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
    region = "cn-hangzhou"
    
    # Set yourBucketName to the name of the bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    key_list = ['yourObject1Name', 'yourObject2Name']
    # After you perform a delete operation without specifying a versionId, a delete marker is added to the object.
    result = bucket.batch_delete_objects(key_list)
    for del_version in result.delete_versions:
        print('key name:', del_version.key)
        # Print the returned delete marker.
        print('Is del marker:', del_version.delete_marker)
        print('key del_marker.versionid', del_version.delete_marker_versionid)

Eliminar archivos con un prefijo específico

A continuación código muestra cómo eliminar archivos que tienen un prefijo específico:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Set yourBucketName to the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
prefix = "yourKeyPrefix"

# List the versionIds of all files with the specified prefix and delete these files.
next_key_marker = None
next_versionid_marker = None
while True:
    result = bucket.list_object_versions(prefix=prefix, key_marker=next_key_marker, versionid_marker=next_versionid_marker)

    for version_info in result.versions:
        bucket.delete_object(version_info.key, params={'versionId': version_info.versionid})

    for del_marker_info in result.delete_marker:
        bucket.delete_object(del_marker_info.key, params={'versionId': del_marker_info.versionid})

    is_truncated = result.is_truncated

    if is_truncated:
        next_key_marker = result.next_key_marker
        next_versionid_marker = result.next_versionid_marker
    else:
        break

Referencias

  • Para obtener más información sobre la operación de API para eliminar un solo archivo, consulte DeleteObject.

  • Para obtener más información sobre la operación de API para eliminar varios archivos, consulte DeleteMultipleObjects.