使用boto3

时间:2016-09-01 13:08:58

标签: python-2.7 amazon-web-services amazon-s3 boto3

我的代码一切正常。我目前面临的唯一陷阱是我无法在S3存储桶中指定我想要放入文件的文件夹。这就是我所拥有的:

s3.meta.client.upload_file('/tmp/'+filename, '<bucket-name>', filename)

我试过了两个:

s3.meta.client.upload_file('/tmp/'+filename, '<bucket-name>/folder/', filename)

s3.meta.client.upload_file('/tmp/'+filename, '<bucket-name>', '/folder/'+filename)

如果有人有关于如何将其指向特定文件夹的任何提示(如果可能的话),请告诉我!

6 个答案:

答案 0 :(得分:26)

您不需要将Key值作为绝对路径传递。以下应该有效:

upload_file('/tmp/' + filename, '<bucket-name>', 'folder/{}'.format(filename))

答案 1 :(得分:3)

我发现了我的问题。我在关键参数区域中使用/folder/选项有了正确的想法,但是,我不需要第一个/谢谢大家!这与hjpotter92的建议基本相同。

答案 2 :(得分:0)

以下是处理嵌套目录结构的方法,并且可以使用boto上传完整目录

def upload_directory():
    for root, dirs, files in os.walk(settings.LOCAL_SYNC_LOCATION):
        nested_dir = root.replace(settings.LOCAL_SYNC_LOCATION, '')
        if nested_dir:
            nested_dir = nested_dir.replace('/','',1) + '/'

        for file in files:
            complete_file_path = os.path.join(root, file)
            file = nested_dir + file if nested_dir else file
            print "[S3_UPLOAD] Going to upload {complete_file_path} to s3 bucket {s3_bucket} as {file}"\
                .format(complete_file_path=complete_file_path, s3_bucket=settings.S3_BUCKET, file=file)
            s3_client.upload_file(complete_file_path, settings.S3_BUCKET, file)

答案 3 :(得分:0)

将其用于python 3.x

s3.upload_file(file_path,bucket_name, '%s/%s' % (bucket_folder,dest_file_name))

答案 4 :(得分:0)

您可以使用put_object代替upload_file

file = open(r"/tmp/" + filename)
response = s3.meta.client.Bucket('<bucket-name>').put_object(Key='folder/{}'.format(filename), Body=file)

答案 5 :(得分:0)

尝试一下:

s3.meta.client.upload_file(Filename=filename_and_full_path, Bucket=my_bucket, Key=prefix_key_plus_filename_only)