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)
【cos】遍历删除所有归档类型
最新推荐文章于 2025-08-05 17:20:40 发布