使用boto将目录上传到s3

use*_*539 9 amazon-s3 amazon-ec2 boto amazon-web-services python-2.7

我已经连接到实例,我想将从我的python脚本生成的文件直接上传到S3.我试过这个:

import boto
s3 = boto.connect_s3()
bucket = s3.get_bucket('alexandrabucket')
from boto.s3.key import Key
key = bucket.new_key('s0').set_contents_from_string('some content')
Run Code Online (Sandbox Code Playgroud)

但这是在创建一个带有上下文"相同内容"的新文件s0,而我想将目录s0上传到mybucket.

我也看了s3put,但我没有得到我想要的东西.

小智 22

以下函数可用于通过 boto 将目录上传到 s3。

    def uploadDirectory(path,bucketname):
        for root,dirs,files in os.walk(path):
            for file in files:
                s3C.upload_file(os.path.join(root,file),bucketname,file)
Run Code Online (Sandbox Code Playgroud)

提供目录和存储桶名称的路径作为输入。文件直接放入存储桶中。更改 upload_file() 函数的最后一个变量以将它们放在“目录”中。

  • 这里有更好的解决方案https://gist.github.com/feelinc/d1f541af4f31d09a2ec3 (6认同)
  • 这个 s3 对象是什么?是 Boto 客户端吗?我看不到任何暴露 upload_file 的内容 (3认同)

gar*_*aat 12

boto库中没有任何内容可以让您上传整个目录.您可以使用os.walk或类似编写自己的代码来遍历目录,并使用boto上传每个单独的文件.

boto中有一个命令行实用程序s3put可以处理这个,或者您可以使用AWS CLI工具,该工具具有许多功能,允许您上载整个目录,甚至可以将S3存储桶与本地目录同步,反之亦然.

  • 使用 os.walk 一次上传每个文件比批量上传慢得多。 (3认同)
  • 谢谢“s3同步”看起来它可以完成这项工作http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html (2认同)

Tob*_*nst 10

s3fs 包提供了很好的功能来处理这种情况

s3_file = s3fs.S3FileSystem()
local_path = "some_dir_path/some_dir_path/"
s3_path = "bucket_name/dir_path"
s3_file.put(local_path, s3_path, recursive=True) 
Run Code Online (Sandbox Code Playgroud)


use*_*227 5

我根据@JDPTET 的反馈构建了该函数,但是,

  1. 我需要删除公共的整个本地路径,以免上传到存储桶!
  2. 不确定我遇到了多少路径分隔符 - 所以我不得不使用os.path.normpath
    def upload_folder_to_s3(s3bucket, inputDir, s3Path):
        print("Uploading results to s3 initiated...")
        print("Local Source:",inputDir)
        os.system("ls -ltR " + inputDir)

        print("Dest  S3path:",s3Path)

        try:
            for path, subdirs, files in os.walk(inputDir):
                for file in files:
                    dest_path = path.replace(inputDir,"")
                    __s3file = os.path.normpath(s3Path + '/' + dest_path + '/' + file)
                    __local_file = os.path.join(path, file)
                    print("upload : ", __local_file, " to Target: ", __s3file, end="")
                    s3bucket.upload_file(__local_file, __s3file)
                    print(" ...Success")
        except Exception as e:
            print(" ... Failed!! Quitting Upload!!")
            print(e)
            raise e

    s3 = boto3.resource('s3', region_name='us-east-1')
    s3bucket = s3.Bucket("<<s3bucket_name>>")
    upload_folder_to_s3(s3bucket, "<<Local Folder>>", "<<s3 Path>>")
Run Code Online (Sandbox Code Playgroud)