You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将S3存储桶内JSON与JPEG文件分类下载到三个指定文件夹

S3文件分类下载实现方案

前置要求

  • 已获得目标S3存储桶的读权限
  • 按需选择使用AWS CLI或者Python工具实现

方法1:使用AWS CLI快速实现(适合固定少量文件场景)

首先先在本地创建三个目标文件夹:

mkdir -p json json_associated_jpeg standalone_jpeg

替换以下命令中的<你的存储桶名称>为实际桶名,依次执行即可:

  1. 下载所有json文件到json文件夹
aws s3 cp s3://<你的存储桶名称>/ ./json/ --exclude "*" --include "1.json" --include "2.json" --include "3.json" --recursive
  1. 下载json对应的关联图片到json_associated_jpeg文件夹
aws s3 cp s3://<你的存储桶名称>/ ./json_associated_jpeg/ --exclude "*" --include "1.jpeg" --include "2.jpeg" --include "3.jpeg" --recursive
  1. 下载无对应json的单独图片到standalone_jpeg文件夹
aws s3 cp s3://<你的存储桶名称>/ ./standalone_jpeg/ --exclude "*" --include "4.jpeg" --include "5.jpeg" --include "6.jpeg" --include "7.jpeg" --recursive

方法2:使用Python + boto3实现(适合文件量大、需要自动识别分类的场景)

首先安装依赖:

pip install boto3

运行以下代码即可自动完成分类下载,无需手动指定文件名:

import boto3
import os

# 自定义配置项,按需修改即可
BUCKET_NAME = "替换为你的S3存储桶名称"
JSON_SAVE_PATH = "./json"
ASSOCIATED_JPEG_SAVE_PATH = "./json_associated_jpeg"
STANDALONE_JPEG_SAVE_PATH = "./standalone_jpeg"

# 初始化S3客户端
s3_client = boto3.client("s3")

# 自动创建本地存储文件夹
for path in [JSON_SAVE_PATH, ASSOCIATED_JPEG_SAVE_PATH, STANDALONE_JPEG_SAVE_PATH]:
    os.makedirs(path, exist_ok=True)

# 获取存储桶内所有文件列表
file_list = []
paginator = s3_client.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket=BUCKET_NAME):
    if "Contents" in page:
        file_list.extend([obj["Key"] for obj in page["Contents"]])

# 提取所有json文件的前缀(文件名不含后缀部分)
json_prefix_set = set()
for file in file_list:
    if file.endswith(".json"):
        file_prefix = file.rsplit(".", 1)[0]
        json_prefix_set.add(file_prefix)
        # 下载json文件到对应目录
        s3_client.download_file(
            Bucket=BUCKET_NAME,
            Key=file,
            Filename=os.path.join(JSON_SAVE_PATH, os.path.basename(file))
        )

# 分类处理所有jpeg文件
for file in file_list:
    if file.endswith(".jpeg"):
        file_prefix = file.rsplit(".", 1)[0]
        if file_prefix in json_prefix_set:
            save_dir = ASSOCIATED_JPEG_SAVE_PATH
        else:
            save_dir = STANDALONE_JPEG_SAVE_PATH
        # 下载文件到对应目录
        s3_client.download_file(
            Bucket=BUCKET_NAME,
            Key=file,
            Filename=os.path.join(save_dir, os.path.basename(file))
        )

说明:该脚本会自动识别所有json文件、匹配对应的关联jpeg,即使后续存储桶内新增文件也可以直接运行,无需修改代码逻辑。

内容的提问来源于stack exchange,提问作者Codu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:15:04