Todos los productos
Search
Centro de documentos

Object Storage Service:Listar objetos con OSS SDK para Python 2.0

Última actualización: Sep 03, 2026

Este tema describe cómo listar todos los objetos de un bucket mediante el SDK de Object Storage Service (OSS) para Python.

Notas de uso

  • El código de ejemplo de este tema utiliza el ID de región cn-hangzhou correspondiente a la región China (Hangzhou). De forma predeterminada, se usa un endpoint público para acceder a los recursos del bucket. Si desea acceder a los recursos del bucket mediante otros servicios de Alibaba Cloud en la misma región donde se encuentra el bucket, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • Para listar objetos, debe contar con el permiso oss:ListObjects. Para obtener más información, consulte Grant a custom policy.

Código de ejemplo

A continuación se muestra un ejemplo de código que ilustra cómo invocar la operación ListObjectsV2 para listar todos los objetos de 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.

Escenarios comunes

Listar todos los objetos de un directorio específico

El siguiente código de ejemplo muestra cómo especificar el parámetro prefix para listar la información de todos los objetos en un directorio determinado, incluido el tamaño del objeto, la hora de última modificación y el nombre del objeto:

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.

Listar objetos cuyos nombres contienen un prefijo específico

El siguiente código de ejemplo muestra cómo especificar el parámetro prefix para listar la información de los objetos cuyos nombres contienen el prefijo indicado, incluido el tamaño del objeto, la hora de última modificación y el nombre del objeto:

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.

Listar un número específico de objetos

El siguiente código de ejemplo muestra cómo especificar el parámetro MaxKeys para listar la información de una cantidad determinada de objetos, incluido el tamaño del objeto, la hora de última modificación y el nombre del objeto:

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.

Listar todos los objetos a partir de una posición específica

El siguiente código de ejemplo muestra cómo configurar el parámetro StartAfter para definir la posición inicial desde la cual comienza la operación de listado. Se devuelven todos los objetos cuyos nombres son alfabéticamente posteriores al valor del parámetro StartAfter.

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.

Referencias

  • Para consultar el código de ejemplo completo utilizado para listar objetos, visite list_objects_v2.py.