[1017] Upload and download all folders into an Amazon S3 bucket
To upload all folders into an Amazon S3 bucket and maintain the same file structure, you can use the Boto3 library. Here’s how:
-
Uploading Folders:
- Use the
upload_file()
function to upload files to your S3 bucket. - Iterate through the local folders and files, and upload them to the corresponding S3 paths.
- Example code snippet:
import boto3, os s3 = boto3.resource('s3') LOCAL_FOLDER_PATH = 'I:\\IMAGERY' BUCKET_NAME = 'li.imagery' S3_PREFIX = 'desired-prefix/' # Optional: Set a prefix for S3 keys def upload_folder(local_path, s3_prefix=''): for root, dirs, files in os.walk(local_path): print(root) for i in range(len(files)): file = files[i] local_file_path = os.path.join(root, file) s3_key = os.path.join(s3_prefix, os.path.relpath(local_file_path, local_path)) if len(local_file_path) < 256: s3.Bucket(BUCKET_NAME).upload_file(local_file_path, s3_key) upload_folder(LOCAL_FOLDER_PATH)
- Use the
-
Downloading with Same Structure:
- To download files from S3 with the same structure, use the
download_file()
method. - Example code snippet:
LOCAL_FOLDER_PATH = r'D:\...\2024\AWS_uploading_downloading\test' def download_all_files(bucket_name, local_path): my_bucket = s3.Bucket(bucket_name) for s3_object in my_bucket.objects.all(): filename = s3_object.key print(filename) # Create necessary folders if "\\" in filename: folder = os.path.dirname(filename) if not os.path.exists(os.path.join(LOCAL_FOLDER_PATH, folder)): os.makedirs(os.path.join(LOCAL_FOLDER_PATH, folder)) my_bucket.download_file(s3_object.key, os.path.join(local_path, filename)) # Usage: download_all_files('li.imagery', LOCAL_FOLDER_PATH)
- To download files from S3 with the same structure, use the
Remember to replace local_folder
, bucket_name
, and other placeholders with your actual values. Happy coding! 😊
分类:
Python Study
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2023-06-28 【844】GADI相关
2021-06-28 【582】QGIS 矢量化 & Python 加载 shapefile
2021-06-28 【581】PyTorch 实现上采样 —— nn.Upsampling
2019-06-28 【418】C语言ADT实现Quack(stack+queue)
2019-06-28 【417】一条语句编译并执行C语言
2016-06-28 【207】WinForm Chart类
2012-06-28 【054】◀▶ JavaScript 语法参考