上传到s3后从本地服务器删除文件

2024-03-28 19:58:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经成功地获得了本地目录,其中本地服务器上的文件上传到了我的tests3 bucket。 当目录被上传到s3时,我希望本地服务器上的那些相同的目录被删除。理想情况下,我希望保留最后添加的10个文件。”因为这些都是从后台过程中主动写出来的,我不想破坏这一点。”

我不是python中最强的,我很难弄清楚如何将删除部分添加到我当前的python脚本中。任何帮助或建议都会有帮助。你知道吗

import os, time, sys
import boto3


s3_resource = boto3.resource("s3", region_name="us-east-2")

def upload_objects():
    try:
        bucket_name = "Testbucket" #s3 bucket name
        root_path = 'C:/Path/Test/' # local folder for upload

        my_bucket = s3_resource.Bucket(bucket_name)

        for path, subdirs, files in os.walk(root_path):
            path = path.replace("\\","/")
            directory_name = path.replace(root_path,"")
            for file in files:
                my_bucket.upload_file(os.path.join(path, file), directory_name+'/'+file)

    except Exception as err:
        print(err)


if __name__ == '__main__':
    upload_objects()

Tags: 文件pathnameimport服务器目录fors3