首页 > 解决方案 > 如何将文件夹中的多张图片上传到 S3 Bucket?

问题描述

我正在尝试在 python 中实现代码以将多个图像上传到 S3 存储桶中。只有一张图片我可以正常做,但是当我实现这个for循环时,开始出现以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'filename.jpg'

这是迄今为止我在 AWS 文档的帮助下能够开发的功能:

def upload_file(path, bucket, object_name=None):
    """
    Upload files to an S3 bucket

    :param bucket: Bucket to upload to
    :param path: Path of the folder with files to upload
    :param object_name: S3 object name. If not specified, then filename is used
    :return: True if file was uploaded, else False
    """

    # S3 bucket connection
    s3_client = boto3.client('s3')

    # List files from a folder
    files = [f for f in listdir(path) if isfile(join(path, f))]

    try:
        # Upload the image
        for file in files:
            s3_client.upload_file(file, bucket, object_name)

    except ClientError as e:
        logging.error(e)
        return False

    return True

如果有人有任何想法来解决这个问题,我很感激。

标签: pythonamazon-web-servicesamazon-s3

解决方案


换行

files = [f for f in listdir(path) if isfile(join(path, f))]

files = [join(path, f) for f in listdir(path) if isfile(join(path, f))]

应该可以解决您的问题。


推荐阅读