Todos os produtos
Search
Central de documentação

Object Storage Service:Listar objetos via OSS SDK for Python 1.0

Última atualização: Jul 03, 2026

O SDK do Object Storage Service (OSS) para 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 SDK do OSS para 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 o SDK do OSS para Python 2.12.0 ou posterior.

Recomendamos o ObjectIteratorV2 devido ao suporte aprimorado para 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 visualizar as descrições dos parâmetros

    Parâmetro

    Tipo

    Obrigatório

    Descrição

    bucket

    oss2.Bucket

    Sim

    O bucket inicializado.

    prefix

    str

    Não

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

    delimiter

    str

    Não

    Delimitador usado para simular uma estrutura de pastas. Geralmente definido como barra normal (/).

    continuation_token

    str

    Não

    Token de paginação. Passe uma string vazia na primeira solicitação. Nas solicitações subsequentes, use o valor next_continuation_token da resposta anterior.

    start_after

    str

    Não

    Especifique 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 no bucket um objeto com o mesmo nome de start_after, ele não será incluído no resultado.

    fetch_owner

    bool

    Não

    Especifique 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

    Não

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

    max_retries

    int

    Não

    Número máximo de tentativas para uma solicitação com falha.

  • Construtor do ObjectIterator

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

    Clique em visualizar as descrições dos parâmetros

    Parâmetro

    Tipo

    Obrigatório

    Descrição

    bucket

    oss2.Bucket

    Sim

    O bucket inicializado.

    prefix

    str

    Não

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

    delimiter

    str

    Não

    Delimitador usado para simular uma estrutura de pastas. Geralmente definido como barra normal (/).

    marker

    str

    Não

    Especifique 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 no bucket um objeto com o mesmo nome de marker, ele não será incluído no resultado.

    max_keys

    int

    Não

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

    max_retries

    int

    Não

    Número máximo de tentativas para uma solicitação com falha.

Exemplos de código

Antes de executar o código, instale o SDK do OSS para Python e configure as variáveis de ambiente para as credenciais de acesso. Para mais informações, consulte Início rápido com o OSS SDK for Python. Uma conta Alibaba Cloud possui todas as permissões por padrão. Se você utilizar um usuário do Resource Access Management (RAM) ou uma função RAM, certifique-se de que o usuário ou a função tenha 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 obter as informações de 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 um número específico 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 contendo quatro objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi e fun/movie/007.avi. A barra normal (/) atua 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 possui o conceito de pastas; todos os elementos são armazenados como objetos. Para criar uma pasta, crie um objeto de zero bytes terminado com barra normal (/). O console do OSS exibe objetos terminados com barra normal (/) como pastas.

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

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

  • Se você também definir delimiter como barra normal (/), a operação listará apenas os objetos e nomes de subdiretórios no nível superior dessa pasta. Objetos localizados dentro dos subdiretórios não serã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 após uma posição inicial específica

Suponha que um bucket contenha 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()