Tous les produits
Search
Centre de documentation

Object Storage Service:List objects (OSS SDK for Python 1.0)

Dernière mise à jour :Aug 18, 2026

Cette rubrique explique comment répertorier les objets dans un bucket avec versioning activé. Vous pouvez lister tous les objets, un nombre défini d'objets ou les objets dont le nom contient un préfixe donné.

Notes

  • Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez Régions et endpoints.

  • Les identifiants d'accès sont récupérés depuis des variables d'environnement. Pour savoir comment configurer ces identifiants, consultez Configurer les identifiants d'accès à l'aide d'OSS SDK for Python 1.0.

  • Cette rubrique illustre la création d'une instance OSSClient à l'aide d'un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation.

  • Pour répertorier les objets, vous devez disposer de l'autorisation oss:ListObjectVersions. Pour plus d'informations, consultez Accorder une politique personnalisée.

Répertorier les versions de tous les objets d'un bucket

L'exemple de code suivant montre comment lister les versions de tous les objets, y compris les marqueurs de suppression, dans un bucket spécifié :

# -*- 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
# List the versions of all objects, including delete markers in the bucket. 
result = bucket.list_object_versions()

# List the versions of all objects in the bucket. 
next_key_marker = None
next_versionid_marker = None
while True:
    result = bucket.list_object_versions(key_marker=next_key_marker, versionid_marker=next_versionid_marker)

    # Display the versions of the listed objects. 
    for version_info in result.versions:
        print('version_info.versionid:', version_info.versionid)
        print('version_info.key:', version_info.key)
        print('version_info.is_latest:', version_info.is_latest)

    # Display the versions of the listed delete markers. 
    for del_maker_Info in result.delete_marker:
        print('del_maker.key:', del_maker_Info.key)
        print('del_maker.versionid:', del_maker_Info.versionid)
        print('del_maker.is_latest:', del_maker_Info.is_latest)

    is_truncated = result.is_truncated

    # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. 
    if is_truncated:
        next_key_marker = result.next_key_marker
        next_versionid_marker = result.next_versionid_marker
    else:
        break

Répertorier les versions des objets dont le nom contient un préfixe spécifié

Le code ci-dessous illustre la liste des versions d'objets dont le nom commence par un préfixe donné :

# -*- 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
# List the versions of all objects, including delete markers in the bucket. 
result = bucket.list_object_versions()

# List the versions of objects whose names contain the test- prefix. 
prefix = 'test-'
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)

    # Display the versions of the listed objects. 
    for version_info in result.versions:
        print('version_info.versionid:', version_info.versionid)
        print('version_info.key:', version_info.key)
        print('version_info.is_latest:', version_info.is_latest)

    # Display the versions of the listed delete markers. 
    for del_maker_Info in result.delete_marker:
        print('del_maker.key:', del_maker_Info.key)
        print('del_maker.versionid:', del_maker_Info.versionid)
        print('del_maker.is_latest:', del_maker_Info.is_latest)

    is_truncated = result.is_truncated

    # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. 
    if is_truncated:
        next_key_marker = result.next_key_marker
        next_versionid_marker = result.next_versionid_marker
    else:
        break

Répertorier les versions d'un nombre spécifié d'objets

Voici un exemple permettant de lister les versions d'un nombre limité d'objets :

# -*- 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
# List the versions of all objects, including delete markers in the bucket. 
result = bucket.list_object_versions()

# List up to 200 object versions. 
max_keys = 200

result = bucket.list_object_versions(max_keys=max_keys)

# Display the versions of the listed objects. 
for version_info in result.versions:
    print('version_info.versionid:', version_info.versionid)
    print('version_info.key:', version_info.key)
    print('version_info.is_latest:', version_info.is_latest)

# Display the versions of the listed delete markers. 
for del_maker_Info in result.delete_marker:
    print('del_maker.key:', del_maker_Info.key)
    print('del_maker.versionid:', del_maker_Info.versionid)
    print('del_maker.is_latest:', del_maker_Info.is_latest)

# Check whether the listing is truncated. 
# If the number of objects in the bucket is greater than 200, the value of is_truncated is True, which indicates that the listing is truncated. If the number of objects in the bucket is smaller than 200, the value of is_truncated is False, which indicates that the listing is not truncated. 
print('is truncated', result.is_truncated)

Répertorier les objets par répertoire

OSS utilise une structure plate pour stocker les objets. Un répertoire est un objet de zéro octet dont le nom se termine par une barre oblique (/). Vous pouvez télécharger et téléverser un répertoire. Par défaut, un objet dont le nom se termine par une barre oblique (/) s'affiche comme un répertoire dans la console OSS.

Spécifiez les paramètres delimiter et prefix dans la requête pour lister les objets par répertoire.

  • Si vous définissez prefix sur un nom de répertoire dans la requête, les objets et sous-répertoires dont le nom contient ce préfixe sont répertoriés.

  • Si vous spécifiez un préfixe et définissez delimiter sur une barre oblique (/) dans la requête, seuls les objets et sous-répertoires commençant par le préfixe indiqué dans le répertoire concerné sont listés. Chaque sous-répertoire apparaît comme un élément unique dans CommonPrefixes. Les objets et répertoires contenus dans ces sous-répertoires ne sont pas listés.

Exemple : un bucket nommé examplebucket contient les objets suivants : oss.jpg, fun/test.jpg, fun/movie/001.avi et fun/movie/007.txt. La barre oblique (/) sert de délimiteur de répertoire. La structure ci-dessous présente les objets et les répertoires du bucket examplebucket.

examplebucket           
 └── oss.jpg
 └── fun               
      └── test.jpg
      └── movie
           └── 001.avi
           └── 007.txt

Les exemples suivants décrivent comment lister les objets dans des répertoires simulés.

  • Répertorier les versions des objets situés dans le répertoire racine d'un bucket

    Le code suivant montre comment lister les versions des objets présents dans le répertoire racine d'un bucket :

    # -*- 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
    region = "cn-hangzhou"
    
    # Specify the name of your bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    # Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
    # List the versions of all objects, including delete markers in the bucket. 
    result = bucket.list_object_versions()
    
    # Specify the forward slash (/) as the delimiter. 
    delimiter = "/"
    next_key_marker = None
    next_versionid_marker = None
    while True:
        result = bucket.list_object_versions(delimiter=delimiter, key_marker=next_key_marker, versionid_marker=next_versionid_marker)
    
        # Display the versions of the listed objects. 
        for version_info in result.versions:
            print('version_info.versionid:', version_info.versionid)
            print('version_info.key:', version_info.key)
            print('version_info.is_latest:', version_info.is_latest)
    
        # Display the versions of the listed delete markers. 
        for del_maker_Info in result.delete_marker:
            print('del_maker.key:', del_maker_Info.key)
            print('del_maker.versionid:', del_maker_Info.versionid)
            print('del_maker.is_latest:', del_maker_Info.is_latest)
    
        # Display the directories whose names end with a forward slash (/). 
        for common_prefix in result.common_prefix:
            print("common_prefix:", common_prefix)
    
        is_truncated = result.is_truncated
    
        # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. 
        if is_truncated:
            next_key_marker = result.next_key_marker
            next_versionid_marker = result.next_versionid_marker
        else:
            break

    Résultat

    ('version_info.versionid:', 'CAEQEhiBgMCw8Y7FqBciIGIzMDE3MTEzOWRiMDRmZmFhMmRlMjljZWI0MWU4****')
    ('version_info.key:', 'oss.jpg')
    ('version_info.is_latest:', True)
    ('common_prefix:', 'fun/')
  • Répertorier les objets et sous-répertoires d'un répertoire spécifié

    L'exemple ci-dessous permet de lister les objets et les sous-répertoires contenus dans un répertoire d'un bucket :

    # -*- 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
    region = "cn-hangzhou"
    
    # Specify the name of your bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    # Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
    # List the versions of all objects including delete markers in a bucket. 
    result = bucket.list_object_versions()
    
    # Set delimiter to a forward slash (/) and prefix to fun/. 
    prefix = "fun/"
    delimiter = "/"
    next_key_marker = None
    next_versionid_marker = None
    while True:
        result = bucket.list_object_versions(prefix=prefix, delimiter=delimiter, key_marker=next_key_marker, versionid_marker=next_versionid_marker)
    
        # Display the versions of the listed objects. 
        for version_info in result.versions:
            print('version_info.versionid:', version_info.versionid)
            print('version_info.key:', version_info.key)
            print('version_info.is_latest:', version_info.is_latest)
    
        # Display the versions of the listed delete markers. 
        for del_maker_Info in result.delete_marker:
            print('del_maker.key:', del_maker_Info.key)
            print('del_maker.versionid:', del_maker_Info.versionid)
            print('del_maker.is_latest:', del_maker_Info.is_latest)
    
        # Display the directories whose names end with a forward slash (/). 
        for common_prefix in result.common_prefix:
            print("common_prefix:", common_prefix)
    
        is_truncated = result.is_truncated
    
        # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. 
        if is_truncated:
            next_key_marker = result.next_key_marker
            next_versionid_marker = result.next_versionid_marker
        else:
            break

    Résultat

    ('version_info.versionid:', 'CAEQFRiBgMCh9JDkrxciIGE3OTNkYzFhYTc2YzQzOTQ4Y2MzYjg2YjQ4ODg*****')
    ('version_info.key:', 'fun/test.jpg')
    ('version_info.is_latest:', True)
    ('commonPrefix:', 'fun/movie/')

Références

Pour plus d'informations sur l'opération API permettant de répertorier les objets, consultez ListObjectVersions (GetBucketVersions).