Tous les produits
Search
Centre de documentation

Object Storage Service:Répertorier les objets à l'aide du SDK OSS pour Python 2.0

Dernière mise à jour :Aug 18, 2026

Cette rubrique explique comment répertorier tous les objets d'un bucket en utilisant le SDK Object Storage Service (OSS) pour Python.

Notes d'utilisation

  • L'exemple de code de cette rubrique utilise l'ID de région cn-hangzhou de la région Chine (Hangzhou). Par défaut, un endpoint public est utilisé pour accéder aux ressources d'un bucket. Si vous souhaitez accéder aux ressources du bucket via d'autres services Alibaba Cloud situés dans la même région que le bucket, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez la page Régions et endpoints.

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

Exemple de code

L'exemple de code suivant montre comment appeler l'opération ListObjectsV2 pour répertorier tous les objets d'un bucket :

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="list objects v2 sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration to the one specified in the command line.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Create a paginator to allow the ListObjectsV2 operation to list objects.
    paginator = client.list_objects_v2_paginator()

    # Traverse each page of the listed objects.
    for page in paginator.iter_page(oss.ListObjectsV2Request(
            bucket=args.bucket
        )
    ):
        # Traverse each object on each page.
        for o in page.contents:
            # Display the name, size, and last modified time of the object.
            print(f'Object: {o.key}, {o.size}, {o.last_modified}')

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Scénarios courants

Répertorier tous les objets d'un répertoire spécifique

L'exemple de code suivant montre comment spécifier le paramètre prefix pour répertorier les informations de tous les objets d'un répertoire spécifique, y compris la taille de l'objet, la date de dernière modification et le nom de l'objet :

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="list objects v2 sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration to the one specified in the command line.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Create a paginator to allow the ListObjectsV2 operation to list objects.
    paginator = client.list_objects_v2_paginator()

    # Traverse each page of the listed objects.
    for page in paginator.iter_page(oss.ListObjectsV2Request(
            bucket=args.bucket,
            prefix="exampledir/", # Set the prefix parameter to exampledir/ to list all objects in the exampledir/ directory.
        )
    ):
        # Traverse each object on each page.
        for o in page.contents:
            # Display the name, size, and last modified time of the object.
            print(f'Object: {o.key}, Size: {o.size}, Last_modified: {o.last_modified}')

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Répertorier les objets dont les noms contiennent un préfixe spécifique

L'exemple de code suivant montre comment spécifier le paramètre prefix pour répertorier les informations des objets dont les noms contiennent le préfixe spécifié, y compris la taille de l'objet, la date de dernière modification et le nom de l'objet :

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="list objects v2 sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration to the one specified in the command line.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Create a paginator to allow the ListObjectsV2 operation to list objects.
    paginator = client.list_objects_v2_paginator()

    # Traverse each page of the listed objects.
    for page in paginator.iter_page(oss.ListObjectsV2Request(
            bucket=args.bucket,
            prefix="my-object-", # Set the prefix parameter to my-object-, which means only objects whose names contain the my-object- prefix are listed.
        )
    ):
        # Traverse each object on each page.
        for o in page.contents:
            # Display the name, size, and last modified time of the object.
            print(f'Object: {o.key}, Size: {o.size}, Last_modified: {o.last_modified}')

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Répertorier un nombre spécifique d'objets

L'exemple de code suivant montre comment spécifier le paramètre MaxKeys pour répertorier les informations d'un nombre spécifique d'objets, y compris la taille de l'objet, la date de dernière modification et le nom de l'objet :

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="list objects v2 sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration to the one specified in the command line.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Create a paginator to allow the ListObjectsV2 operation to list objects.
    paginator = client.list_objects_v2_paginator()

    # Traverse each page of the listed objects.
    for page in paginator.iter_page(oss.ListObjectsV2Request(
            bucket=args.bucket,
            max_keys=10, # Specify that up to 10 objects can be returned per page.
        )
    ):
        # Traverse each object on each page.
        for o in page.contents:
            # Display the name, size, and last modified time of the object.
            print(f'Object: {o.key}, Size: {o.size}, Last_modified: {o.last_modified}')

        print('-' * 30)

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Répertorier tous les objets à partir d'une position spécifique

L'exemple de code suivant montre comment configurer le paramètre StartAfter pour spécifier la position de départ à partir de laquelle l'opération de liste commence. Tous les objets dont les noms sont alphabétiquement postérieurs à la valeur du paramètre StartAfter sont renvoyés.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="list objects v2 sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration to the one specified in the command line.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Create a paginator to allow the ListObjectsV2 operation to list objects.
    paginator = client.list_objects_v2_paginator()

    # Traverse each page of the listed objects.
    for page in paginator.iter_page(oss.ListObjectsV2Request(
            bucket=args.bucket,
            start_after="my-object", # Specify that objects whose names are alphabetically after my-object are listed.
        )
    ):
        # Traverse each object on each page.
        for o in page.contents:
            # Display the name, size, and last modified time of the object.
            print(f'Object: {o.key}, Size: {o.size}, Last_modified: {o.last_modified}')

        print('-' * 30)

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Références

  • Pour obtenir l'exemple de code complet utilisé pour répertorier les objets, consultez la page list_objects_v2.py.