【cos】遍历删除所有归档类型

import sys
import logging
from venv import logger
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

# 配置日志输出,方便查看过程中的报错等信息
logging.basicConfig(level=logging.WARN, stream=sys.stdout)

# 腾讯云COS配置信息
secret_id = 'xxx'  # 替换为你的 SecretId
secret_key = 'xxx'  # 替换为你的 SecretKey
region = 'na-siliconvalley'  # 替换为你的存储桶所在的地域
bucket = 'xxx'  # 替换为你的存储桶名称

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
client = CosS3Client(config)

def delete_archive_and_deeparchive_files(bucket_name):
    try:
        total_files = 0  # 总文件数
        archive_files = 0  # 归档文件数
        total_archive_size = 0  # 文件总大小(字节)

        marker = ''

        while True:
            logger.warning(f'total={total_files}, archive={archive_files}, archive_size={total_archive_size}')

            result = client.list_objects(Bucket=bucket_name, Marker=marker)

            if 'Contents' not in result:
                logger.error("No more files found in the bucket.")
                break

            for content in result['Contents']:
                total_files += 1
                key = content['Key']

                if content['StorageClass'] == 'ARCHIVE':
                    archive_files += 1
                    total_archive_size += int(content['Size'])

                    client.delete_object(Bucket=bucket_name, Key=key)
                    logger.warning(f"Deleted: {key}")
                    #sys.exit(0)

            # 判断是否还有更多文件
            if 'NextMarker' in result:
                marker = result['NextMarker']
            else:
                break

        # 输出统计信息
        logger.warning(f"Total files scanned: {total_files}")
        logger.warning(f"Total archive files deleted: {archive_files}")
        logger.warning(f"Total size of deleted files: {total_archive_size / (1024 * 1024):.2f} MB")

    except Exception as e:
        logger.error(f"Error occurred: {e}")

# 调用函数删除归档和深度归档类型的文件,并统计结果
delete_archive_and_deeparchive_files(bucket)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值