首页 > 解决方案 > 如何使用python上传文件或文件夹

问题描述

我想Python每隔 x 小时上传一次文件或文件夹,但是我想上传的文件夹每x分钟更新一次,最好的方法是只上传这个尚未上传的文件,我的意思是不上传相同的文件,只上传新的文件。

boto用来上传我的文件S3 Bucket

import boto3
from botocore.exceptions import NoCredentialsError

ACCESS_KEY = 'xxxxxxxxxxxxxxxxx'
SECRET_KEY = 'xxxxxxxxxxxxxxxxx+4Tr4nUp'

def upload_to_aws(local_file, bucket, s3_file):
    s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY,
                      aws_secret_access_key=SECRET_KEY)

    try:
        s3.upload_file(local_file, bucket, s3_file)
        print("Upload Successful")
        return True
    except FileNotFoundError:
        print("The file was not found")
        return False
    except NoCredentialsError:
        print("Credentials not available")
        return False


uploaded = upload_to_aws('test.jpg', 'testverifcation', 'test.jpg')

标签: pythonboto3

解决方案


您可以使用以下方式获取当前存储在存储桶中的所有对象

objectlist = s3.list_objects(Bucket = 'testverifcation')

然后检查文件是否已经在存储桶中,例如

filename = "test.jpg"
if filename in objectlist:
    #file exists so no need to upload
    

推荐阅读