Todos os produtos
Search
Central de documentação

Object Storage Service:List objects via OSS SDK for Python 1.0

Última atualização: Sep 25, 2026

O Object Storage Service (OSS) SDK for Python fornece iteradores encapsulados para listar objetos em um bucket. Use esses iteradores para filtrar objetos por prefixo, posição inicial e outros critérios.

Uso

O OSS SDK for Python oferece dois iteradores para listar objetos: ObjectIterator, baseado na operação GetBucket (ListObjects), e ObjectIteratorV2, baseado na operação ListObjectsV2 (GetBucketV2). As principais diferenças são:

  • ObjectIterator: Retorna as informações do proprietário por padrão.

  • ObjectIteratorV2: Usa o parâmetro fetch_owner para especificar se as informações do proprietário devem ser retornadas.

    O uso do ObjectIteratorV2 requer OSS SDK for Python 2.12.0 ou versão posterior.

Recomendamos o ObjectIteratorV2 pelo suporte aprimorado a buckets com versionamento ativado.

  • Construtor do ObjectIteratorV2

    oss2.ObjectIteratorV2(bucket, prefix='', delimiter='', continuation_token='', start_after='', fetch_owner=False, encoding_type = 'url', max_keys=100, max_retries=None, headers=None)

    Clique em para visualize the parameter descriptions

    Parameter

    Type

    Required

    Description

    bucket

    oss2.Bucket

    Yes

    O bucket inicializado.

    prefix

    str

    No

    Especifica um prefixo para filtrar os nomes dos objetos. O valor padrão é uma string vazia, que retorna todos os objetos.

    delimiter

    str

    No

    O delimitador usado para simular uma estrutura de pastas. Normalmente definido como barra (/).

    continuation_token

    str

    No

    O token de paginação. Passe uma string vazia na primeira requisição. Nas requisições seguintes, use o valor de next_continuation_token retornado pela resposta anterior.

    start_after

    str

    No

    Define o ponto de partida para uma operação de listagem paginada. A operação retorna todos os objetos cujos nomes são lexicograficamente maiores que a string especificada. Mesmo que exista um objeto com o mesmo nome que start_after no bucket, ele não é incluído no resultado.

    fetch_owner

    bool

    No

    Especifica se as informações do proprietário devem ser incluídas nos resultados. Valores válidos:- True: Retorna as informações do proprietário.- False (padrão): Não retorna as informações do proprietário.

    max_keys

    int

    No

    O número máximo de objetos a retornar em uma única resposta. O padrão é 100 e o máximo é 1000.

    max_retries

    int

    No

    O número máximo de tentativas para uma requisição com falha.

  • Construtor do ObjectIterator

    oss2.ObjectIterator(bucket, prefix='', delimiter='', marker='', max_keys=100, max_retries=None, headers=None)

    Clique em para visualize the parameter descriptions

    Parameter

    Type

    Required

    Description

    bucket

    oss2.Bucket

    Yes

    O bucket inicializado.

    prefix

    str

    No

    Especifica um prefixo para filtrar os nomes dos objetos. O valor padrão é uma string vazia, que retorna todos os objetos.

    delimiter

    str

    No

    O delimitador usado para simular uma estrutura de pastas. Normalmente definido como barra (/).

    marker

    str

    No

    Define o ponto de partida para uma operação de listagem paginada. A operação retorna todos os objetos cujos nomes são lexicograficamente maiores que a string especificada. Mesmo que exista um objeto com o mesmo nome que marker no bucket, ele não é incluído no resultado.

    max_keys

    int

    No

    O número máximo de objetos a retornar em uma única resposta. O padrão é 100 e o máximo é 1000.

    max_retries

    int

    No

    O número máximo de tentativas para uma requisição com falha.

Exemplos de código

Antes de executar o código, instale o OSS SDK for Python e configure as variáveis de ambiente para as credenciais de acesso. Para obter mais informações, consulte Quick start with OSS SDK for Python. Uma conta da Alibaba Cloud tem todas as permissões por padrão. Ao usar um usuário RAM (Resource Access Management) ou uma função RAM, verifique se o usuário ou a função tem a permissão oss:ListObjects.

Listar todos os objetos

ObjectIteratorV2 (Recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects in the bucket.
    print("List all objects:")
    for obj in oss2.ObjectIteratorV2(bucket):
        print(f"Object name: {obj.key}, Size: {obj.size} bytes")

if __name__ == "__main__":
    main()

Para recuperar as informações do proprietário dos objetos, defina fetch_owner=True.

# List all objects and get their owner information.
for obj in oss2.ObjectIteratorV2(bucket, fetch_owner=True):
    print(f"Object name: {obj.key}")
    print(f"Owner name: {obj.owner.display_name}")
    print(f"Owner ID: {obj.owner.id}")

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects in the bucket.
    print("List all objects:")
    for obj in oss2.ObjectIterator(bucket):
        print(f"Object name: {obj.key}, Size: {obj.size} bytes")

if __name__ == "__main__":
    main()

Listar uma quantidade específica de objetos

ObjectIteratorV2 (Recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List the first 10 objects in the bucket.
    print("List the first 10 objects:")
    for obj in islice(oss2.ObjectIteratorV2(bucket), 10):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List the first 10 objects in the bucket.
    print("List the first 10 objects:")
    for obj in islice(oss2.ObjectIterator(bucket), 10):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

Listar objetos com um prefixo específico

Considere um bucket com quatro objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi e fun/movie/007.avi. A barra (/) é usada como separador de pastas.

ObjectIteratorV2 (Recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
    
    # List all objects in the fun folder, including objects in its subdirectories.
    print("List all objects with the prefix fun/:")
    for obj in oss2.ObjectIteratorV2(bucket, prefix='fun/'):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

Saída esperada:

List all objects with the prefix fun/:
Object name: fun/
Object name: fun/movie/
Object name: fun/movie/001.avi
Object name: fun/movie/007.avi
Object name: fun/test.jpg

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
    
    # List all objects in the fun folder, including objects in its subdirectories.
    print("List all objects with the prefix fun/:")
    for obj in oss2.ObjectIterator(bucket, prefix='fun/'):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

Saída esperada:

List all objects with the prefix fun/:
Object name: fun/
Object name: fun/movie/
Object name: fun/movie/001.avi
Object name: fun/movie/007.avi
Object name: fun/test.jpg

Listar objetos e subdiretórios em um diretório específico

O OSS não tem o conceito de pastas. Todos os elementos são armazenados como objetos. Para crie uma pasta, crie um objeto de zero bytes cujo nome termine com barra (/). O console do OSS exibe como pastas os objetos cujos nomes terminam com barra (/).

Use os parâmetros delimiter e prefix para simular a funcionalidade de pastas.

  • Ao defina prefix com o nome de uma pasta, a operação lista todos os objetos cujas chaves começam com esse prefixo, percorrendo recursivamente todo o conteúdo da pasta simulada.

  • Ao defina também delimiter como barra (/), a operação lista apenas os objetos e nomes de subdiretórios no nível superior dessa pasta. Os objetos nos subdiretórios não são listados.

ObjectIteratorV2 (Recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
    
    # List the objects and subfolder names in the fun folder, but not the objects within the subfolders.
    print("List objects and subdirectories in the fun directory:")
    for obj in oss2.ObjectIteratorV2(bucket, prefix='fun/', delimiter='/', start_after='fun/'):
        # Use the is_prefix method to determine whether the obj is a folder.
        if obj.is_prefix():
            print(f"Subdirectory: {obj.key}")
        else:
            print(f"Object: {obj.key}")

if __name__ == "__main__":
    main()

Saída esperada:

List objects and subdirectories in the fun directory:
Subdirectory: fun/movie/
Object: fun/test.jpg

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
    
    # List the objects and subfolder names in the fun folder, but not the objects within the subfolders.
    print("List objects and subdirectories in the fun directory:")
    for obj in oss2.ObjectIterator(bucket, prefix='fun/', delimiter='/', marker='fun/'):
        # Use the is_prefix method to determine whether the obj is a folder.
        if obj.is_prefix():
            print(f"Subdirectory: {obj.key}")
        else:
            print(f"Object: {obj.key}")

if __name__ == "__main__":
    main()

Saída esperada:

List objects and subdirectories in the fun directory:
Subdirectory: fun/movie/
Object: fun/test.jpg

Listar objetos a partir de uma posição inicial específica

Considere um bucket com os seguintes quatro objetos: x1.txt, x2.txt, z1.txt e z2.txt.

ObjectIteratorV2 (Recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
    
    # List all objects after x2.txt (excluding x2.txt itself).
    print("List all objects after x2.txt:")
    for obj in oss2.ObjectIteratorV2(bucket, start_after="x2.txt"):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

Saída esperada:

List all objects after x2.txt:
Object name: z1.txt
Object name: z2.txt

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
    
    # List all objects after x2.txt (excluding x2.txt itself).
    print("List all objects after x2.txt:")
    for obj in oss2.ObjectIterator(bucket, marker="x2.txt"):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

Saída esperada:

List all objects after x2.txt:
Object name: z1.txt
Object name: z2.txt

Obter o tamanho dos objetos em um diretório específico

ObjectIteratorV2 (Recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def calculate_folder_size(bucket, folder):
    """Calculate the total size of a specified folder."""
    total_size = 0
    for obj in oss2.ObjectIteratorV2(bucket, prefix=folder):
        total_size += obj.size
    return total_size

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
    
    # List all objects and folders in the root directory and display their sizes.
    print("List the sizes of objects and folders in the root directory:")
    for obj in oss2.ObjectIteratorV2(bucket, delimiter='/'):
        if obj.is_prefix():
            # Calculate the total size of the folder.
            folder_size = calculate_folder_size(bucket, obj.key)
            print(f"Directory: {obj.key}, Size: {folder_size} bytes")
        else:
            # Display the object size directly.
            print(f"Object: {obj.key}, Size: {obj.size} bytes")

if __name__ == "__main__":
    main()

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def calculate_folder_size(bucket, folder):
    """Calculate the total size of a specified folder."""
    total_size = 0
    for obj in oss2.ObjectIterator(bucket, prefix=folder):
        total_size += obj.size
    return total_size

def main():
    # Get access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
    
    # List all objects and folders in the root directory and display their sizes.
    print("List the sizes of objects and folders in the root directory:")
    for obj in oss2.ObjectIterator(bucket, delimiter='/'):
        if obj.is_prefix():
            # Calculate the total size of the folder.
            folder_size = calculate_folder_size(bucket, obj.key)
            print(f"Directory: {obj.key}, Size: {folder_size} bytes")
        else:
            # Display the object size directly.
            print(f"Object: {obj.key}, Size: {obj.size} bytes")

if __name__ == "__main__":
    main()