Boto3 文件夹在新的 S3“文件夹”下同步

Arc*_*ist 1 python amazon-s3 boto3

所以,在有人告诉我 S3 的平面结构之前,我已经知道了,但事实是您可以在 S3 中创建“文件夹”。我使用此 Python 代码的目标是创建一个使用运行日期命名的新文件夹,并将用户的输入附加到此(即 createS3Folder 函数) - 然后我想将本地目录中的文件夹同步到该文件夹​​。

问题是我的 upload_files 函数在 S3 中创建了一个新文件夹,它完全模拟了我本地设置的文件夹结构。

谁能建议我如何在不更改名称的情况下将文件夹同步到新创建的文件夹中?

import sys
import boto3
import datetime
import os

teamName = raw_input("Please enter the name of your project: ")
bucketFolderName = ""

def createS3Folder():
    date = datetime.date.today().strftime("%Y") + "." + 
    datetime.date.today().strftime("%B") + "." + 
    datetime.date.today().strftime("%d")
    date1 = datetime.date.today()
    date = str(date1) + "/" #In order to generate a file, you must 
    put "/" at the end of key
    bucketFolderName = date + teamName + "/"  
    client = boto3.client('s3')
    client.put_object(Bucket='MY_BUCKET',Key=bucketFolderName)  
    upload_files('/Users/local/directory/to/sync')

def upload_files(path):
    session = boto3.Session()
    s3 = session.resource('s3')
    bucket = s3.Bucket('MY_BUCKET')
    for subdir, dirs, files in os.walk(path):
        for file in files:
            full_path = os.path.join(subdir, file)
            with open(full_path, 'rb') as data:
                bucket.put_object(Key=bucketFolderName, Body=data)

def main():
    createS3Folder()

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

Joh*_*ein 5

您的upload_files()函数正在上传到:

bucket.put_object(Key=bucketFolderName, Body=data)
Run Code Online (Sandbox Code Playgroud)

这意味着 S3 上的文件名(“密钥”)将是“文件夹”的名称。它应该是:

 bucket.put_object(Key=bucketFolderName + '/' + file, Body=data)
Run Code Online (Sandbox Code Playgroud)

Key 是目标对象的完整路径,包括文件名(不仅仅是“目录”)。

事实上,无需事先创建“文件夹”——只需上传到所需的密钥即可。

如果您觉得懒惰,请使用AWS 命令​​行界面 (CLI) aws s3 sync命令为您完成!