Todos os produtos
Search
Central de documentação

Object Storage Service:Manage folders (Python SDK V1)

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) usa uma estrutura plana para armazenar objetos, em vez da estrutura hierárquica comum em sistemas de arquivos tradicionais. Todos os dados no OSS são armazenados como objetos em buckets. O console do OSS exibe objetos cujos nomes terminam com barra (/) como diretórios, semelhantes a pastas em sistemas de arquivos. Use diretórios para organizar objetos hierarquicamente e simplificar o controle de acesso.

Observações

  • Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações, consulte Regiões e endpoints.

  • Este tópico obtém credenciais de acesso de variáveis de ambiente. Para saber mais sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso usando o OSS SDK for Python 1.0.

  • Este tópico cria uma instância OSSClient usando um endpoint do OSS. Para criar uma instância OSSClient com domínios personalizados ou Security Token Service (STS), consulte Inicialização.

Criar diretórios

O código de exemplo a seguir mostra como criar um diretório:

# -*- 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 for 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, "examplebucket", region=region)

# Specify the name of the directory. The directory name must end with a forward slash. 
bucket.put_object('exampledir/', '')

Listar diretórios

O código de exemplo a seguir mostra como listar todos os subdiretórios no diretório raiz:

# -*- 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 for 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, "examplebucket", region=region)

# List directories
def list_directories(bucket, prefix='', delimiter='/'):
    result = bucket.list_objects_v2(prefix=prefix, delimiter=delimiter)
    directories = []

    # Obtain the directory at the current level.
    for common_prefix in result.prefix_list:
        directories.append(common_prefix)

    return directories

# Invoke the function to obtain all subdirectories in the root directory.
directories = list_directories(bucket)
print("Directory list:", directories)

Excluir diretórios

Aviso

Excluir um diretório remove simultaneamente todos os subdiretórios e objetos contidos nele. Proceda com cautela.

O código de exemplo a seguir mostra como excluir um diretório chamado log e todos os objetos dentro dele do examplebucket:

# -*- 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 for 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, "examplebucket", region=region)
prefix = "exampledir/"

# Delete the directory and all objects stored within. 
for obj in oss2.ObjectIterator(bucket, prefix=prefix):
    bucket.delete_object(obj.key)

Tópicos relacionados

  • Criar diretórios

    Para a operação de API usada para criar um diretório, consulte PutObject.

  • Excluir diretórios

    • Para obter o código de exemplo completo que exclui um diretório e todos os objetos dentro dele, visite o repositório aliyun-oss-python-sdk.

    • Para a operação de API usada para excluir um diretório e todos os objetos dentro dele, consulte DeleteObject.