alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[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:

  1. 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)
  2. 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)

Remember to replace local_folder, bucket_name, and other placeholders with your actual values. Happy coding! 😊

 
 

posted on   McDelfino  阅读(11)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 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 语法参考
点击右上角即可分享
微信分享提示