Todos os produtos
Search
Central de documentação

Object Storage Service:List objects (OSS SDK for Python 1.0)

Última atualização: Sep 24, 2026

Este tópico descreve como listar objects em um bucket com versionamento ativo. É possível listar todos os objects, um número específico de objects e objects cujos nomes contenham um prefixo determinado.

Observações

  • Neste tópico, o endpoint público da região china (Hangzhou) é utilizado. Para acessar o OSS a partir de outros services da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Neste tópico, as credenciais de acesso são obtidas a partir de variáveis de ambiente. Para obter mais informações sobre como configure credenciais de acesso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Initialization.

  • Para listar objects, é necessário ter a permissão oss:ListObjectVersions. Para obter mais informações, consulte Grant a custom policy.

Listar as versões de todos os objects em um bucket

O código a seguir apresenta um exemplo de como listar as versões de todos os objects, incluindo delete markers, em um bucket específico:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
# List the versions of all objects, including delete markers in the bucket. 
result = bucket.list_object_versions()

# List the versions of all objects in the bucket. 
next_key_marker = None
next_versionid_marker = None
while True:
    result = bucket.list_object_versions(key_marker=next_key_marker, versionid_marker=next_versionid_marker)

    # Display the versions of the listed objects. 
    for version_info in result.versions:
        print('version_info.versionid:', version_info.versionid)
        print('version_info.key:', version_info.key)
        print('version_info.is_latest:', version_info.is_latest)

    # Display the versions of the listed delete markers. 
    for del_maker_Info in result.delete_marker:
        print('del_maker.key:', del_maker_Info.key)
        print('del_maker.versionid:', del_maker_Info.versionid)
        print('del_maker.is_latest:', del_maker_Info.is_latest)

    is_truncated = result.is_truncated

    # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. 
    if is_truncated:
        next_key_marker = result.next_key_marker
        next_versionid_marker = result.next_versionid_marker
    else:
        break

Listar as versões de objects cujos nomes contenham um prefixo específico

O código a seguir apresenta um exemplo de como listar as versões de objects cujos nomes contenham um prefixo específico:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
# List the versions of all objects, including delete markers in the bucket. 
result = bucket.list_object_versions()

# List the versions of objects whose names contain the test- prefix. 
prefix = 'test-'
next_key_marker = None
next_versionid_marker = None
while True:
    result = bucket.list_object_versions(prefix=prefix, key_marker=next_key_marker, versionid_marker=next_versionid_marker)

    # Display the versions of the listed objects. 
    for version_info in result.versions:
        print('version_info.versionid:', version_info.versionid)
        print('version_info.key:', version_info.key)
        print('version_info.is_latest:', version_info.is_latest)

    # Display the versions of the listed delete markers. 
    for del_maker_Info in result.delete_marker:
        print('del_maker.key:', del_maker_Info.key)
        print('del_maker.versionid:', del_maker_Info.versionid)
        print('del_maker.is_latest:', del_maker_Info.is_latest)

    is_truncated = result.is_truncated

    # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. 
    if is_truncated:
        next_key_marker = result.next_key_marker
        next_versionid_marker = result.next_versionid_marker
    else:
        break

Listar as versões de um número específico de objects

O código a seguir apresenta um exemplo de como listar as versões de uma quantidade específica de objects:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
# List the versions of all objects, including delete markers in the bucket. 
result = bucket.list_object_versions()

# List up to 200 object versions. 
max_keys = 200

result = bucket.list_object_versions(max_keys=max_keys)

# Display the versions of the listed objects. 
for version_info in result.versions:
    print('version_info.versionid:', version_info.versionid)
    print('version_info.key:', version_info.key)
    print('version_info.is_latest:', version_info.is_latest)

# Display the versions of the listed delete markers. 
for del_maker_Info in result.delete_marker:
    print('del_maker.key:', del_maker_Info.key)
    print('del_maker.versionid:', del_maker_Info.versionid)
    print('del_maker.is_latest:', del_maker_Info.is_latest)

# Check whether the listing is truncated. 
# If the number of objects in the bucket is greater than 200, the value of is_truncated is True, which indicates that the listing is truncated. If the number of objects in the bucket is smaller than 200, the value of is_truncated is False, which indicates that the listing is not truncated. 
print('is truncated', result.is_truncated)

Listar objects por diretório

O OSS utiliza uma estrutura plana para armazenar objects. Um diretório é um object de zero bytes cujo nome termina com uma barra (/). É possível fazer upload e baixe de um diretório. Por padrão, um object cujo nome termina com barra (/) é exibido como um diretório no console do OSS.

Para listar objects por diretório, especifique os parâmetros delimiter e prefix na requisição.

  • Ao defina prefix com o nome de um diretório na requisição, são listados os objects e subdiretórios cujos nomes contenham esse prefixo.

  • Ao especifique um prefix e defina delimiter como barra (/) na requisição, são listados os objects e subdiretórios cujos nomes comecem com o prefixo indicado dentro do diretório. Cada subdiretório aparece como um único elemento de resultado em CommonPrefixes. Os objects e diretórios contidos nesses subdiretórios não são listados.

Exemplo: um bucket chamado examplebucket contém os seguintes objects: oss.jpg, fun/test.jpg, fun/movie/001.avi e fun/movie/007.txt. A barra (/) é usada como delimitador de diretório. A estrutura a seguir exibe os objects e os diretórios do bucket examplebucket.

examplebucket           
 └── oss.jpg
 └── fun               
      └── test.jpg
      └── movie
           └── 001.avi
           └── 007.txt

Os exemplos a seguir descrevem como listar objects em diretórios simulados.

  • Listar as versões de objects no diretório raiz de um bucket

    O código a seguir apresenta um exemplo de como listar as versões de objects no diretório raiz de um bucket:

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
    region = "cn-hangzhou"
    
    # Specify the name of your bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    # Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
    # List the versions of all objects, including delete markers in the bucket. 
    result = bucket.list_object_versions()
    
    # Specify the forward slash (/) as the delimiter. 
    delimiter = "/"
    next_key_marker = None
    next_versionid_marker = None
    while True:
        result = bucket.list_object_versions(delimiter=delimiter, key_marker=next_key_marker, versionid_marker=next_versionid_marker)
    
        # Display the versions of the listed objects. 
        for version_info in result.versions:
            print('version_info.versionid:', version_info.versionid)
            print('version_info.key:', version_info.key)
            print('version_info.is_latest:', version_info.is_latest)
    
        # Display the versions of the listed delete markers. 
        for del_maker_Info in result.delete_marker:
            print('del_maker.key:', del_maker_Info.key)
            print('del_maker.versionid:', del_maker_Info.versionid)
            print('del_maker.is_latest:', del_maker_Info.is_latest)
    
        # Display the directories whose names end with a forward slash (/). 
        for common_prefix in result.common_prefix:
            print("common_prefix:", common_prefix)
    
        is_truncated = result.is_truncated
    
        # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. 
        if is_truncated:
            next_key_marker = result.next_key_marker
            next_versionid_marker = result.next_versionid_marker
        else:
            break

    Result

    ('version_info.versionid:', 'CAEQEhiBgMCw8Y7FqBciIGIzMDE3MTEzOWRiMDRmZmFhMmRlMjljZWI0MWU4****')
    ('version_info.key:', 'oss.jpg')
    ('version_info.is_latest:', True)
    ('common_prefix:', 'fun/')
  • Listar os objects e subdiretórios de um diretório específico

    O código a seguir apresenta um exemplo de como listar os objects e subdiretórios de um diretório em um bucket:

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
    region = "cn-hangzhou"
    
    # Specify the name of your bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    # Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. 
    # List the versions of all objects including delete markers in a bucket. 
    result = bucket.list_object_versions()
    
    # Set delimiter to a forward slash (/) and prefix to fun/. 
    prefix = "fun/"
    delimiter = "/"
    next_key_marker = None
    next_versionid_marker = None
    while True:
        result = bucket.list_object_versions(prefix=prefix, delimiter=delimiter, key_marker=next_key_marker, versionid_marker=next_versionid_marker)
    
        # Display the versions of the listed objects. 
        for version_info in result.versions:
            print('version_info.versionid:', version_info.versionid)
            print('version_info.key:', version_info.key)
            print('version_info.is_latest:', version_info.is_latest)
    
        # Display the versions of the listed delete markers. 
        for del_maker_Info in result.delete_marker:
            print('del_maker.key:', del_maker_Info.key)
            print('del_maker.versionid:', del_maker_Info.versionid)
            print('del_maker.is_latest:', del_maker_Info.is_latest)
    
        # Display the directories whose names end with a forward slash (/). 
        for common_prefix in result.common_prefix:
            print("common_prefix:", common_prefix)
    
        is_truncated = result.is_truncated
    
        # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. 
        if is_truncated:
            next_key_marker = result.next_key_marker
            next_versionid_marker = result.next_versionid_marker
        else:
            break

    Result

    ('version_info.versionid:', 'CAEQFRiBgMCh9JDkrxciIGE3OTNkYzFhYTc2YzQzOTQ4Y2MzYjg2YjQ4ODg*****')
    ('version_info.key:', 'fun/test.jpg')
    ('version_info.is_latest:', True)
    ('commonPrefix:', 'fun/movie/')

Referências

Para obter mais informações sobre a operação de API disponível para listar objects, consulte ListObjectVersions (GetBucketVersions).