Todos os produtos
Search
Central de documentação

Object Storage Service:Listar objetos com o OSS SDK for Python 2.0

Última atualização: Jul 03, 2026

Este tópico descreve como listar todos os objetos em um bucket usando o Object Storage Service (OSS) SDK for Python.

Observações de uso

  • O código de exemplo neste tópico utiliza o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o acesso aos recursos do bucket ocorre via endpoint público. Caso precise acessar esses recursos por meio de outros serviços da Alibaba Cloud na mesma região do bucket, utilize um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Para listar objetos, é necessária a permissão oss:ListObjects. Para obter mais informações, veja Conceder uma política personalizada.

Código de exemplo

O exemplo abaixo demonstra como chamar a operação ListObjectsV2 para relacionar todos os objetos existentes em um 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.

Cenários comuns

Listar todos os objetos em um diretório específico

O código a seguir ilustra como definir o parâmetro prefix para obter informações de todos os objetos dentro de um diretório determinado, incluindo tamanho, data de última modificação e nome do 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 cujos nomes contêm um prefixo específico

Neste exemplo, o parâmetro prefix filtra e lista apenas os objetos que possuem o prefixo indicado no nome, retornando também tamanho, última modificação e nome completo:

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 uma quantidade específica de objetos

Utilize o parâmetro MaxKeys conforme o trecho abaixo para limitar o número de objetos retornados, exibindo detalhes como tamanho, data de modificação e nome:

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 os objetos a partir de uma posição específica

Configure o parâmetro StartAfter para estabelecer o ponto inicial da listagem. A operação retornará todos os objetos cujos nomes venham depois do valor definido em StartAfter, seguindo a ordem alfabética.

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.

Referências

  • Para acessar o código de exemplo completo sobre listagem de objetos, visite list_objects_v2.py.