Python 批量移动 S3 对象
需求
将 S3 中的文件路径从:
s3://foobar/expense/2023/12/02 00:00:00/2023-12-02 00:00:00.json
移动为:
s3://foobar/expense/2023/12/02/2023-12-02.json
需要处理从某个日期到今天的所有文件。
实现方式
S3 没有直接的”移动”操作,需要先复制(COPY)再删除(DELETE)原对象。
安装依赖
pip install boto3
Python 脚本
import boto3
import datetime
# 初始化 S3 客户端
s3_client = boto3.client('s3')
# S3 桶名称
bucket_name = 'foobar'
# 设定日期范围
start_date = datetime.datetime(2023, 12, 1)
end_date = datetime.datetime.now()
# 遍历日期范围
current_date = start_date
while current_date <= end_date:
# 构建原始和目标键
original_key = f'expense/{current_date.year}/{current_date.month:02d}/{current_date.day:02d} 00:00:00/{current_date.strftime("%Y-%m-%d")} 00:00:00.json'
new_key = f'expense/{current_date.year}/{current_date.month:02d}/{current_date.day:02d}/{current_date.strftime("%Y-%m-%d")}.json'
# 复制对象
copy_source = {
'Bucket': bucket_name,
'Key': original_key
}
try:
s3_client.copy(copy_source, bucket_name, new_key)
print(f'Copied: {original_key} to {new_key}')
# 删除原始对象
s3_client.delete_object(Bucket=bucket_name, Key=original_key)
print(f'Deleted: {original_key}')
except s3_client.exceptions.NoSuchKey:
print(f'No such key: {original_key}')
except Exception as e:
print(f'Error: {e}')
# 移至下一天
current_date += datetime.timedelta(days=1)
注意事项
- 确保 AWS 凭证已配置(环境变量或
.aws/credentials文件) - 需要有足够的 S3 操作权限(复制和删除)
- 运行前建议备份重要数据
- 大量文件时可能需要处理 S3 分页响应