【问题标题】:Python - Finding path of a file on cloud9 AWS (boto3)Python - 在 cloud9 AWS (boto3) 上查找文件的路径
【发布时间】:2021-06-24 11:29:08
【问题描述】:

我正在尝试将一个对象放入 cloud9 环境中的 S3 存储桶中 该文件位于 IDE 内的同一文件夹中。 我有一个名为 project1 的文件夹,这个脚本和文件在同一个文件夹中 这是我的代码

 import logging
    import boto3
    from botocore.exceptions import ClientError


def put_object(dest_bucket_name, dest_object_name, src_data):
    """
    Add an object to an Amazon S3 bucket

    The src_data argument must be of type bytes or a string that references
    a file specification.

    :param dest_bucket_name: string
    :param dest_object_name: string
    :param src_data: bytes of data or string reference to file spec
    :return: True if src_data was added to dest_bucket/dest_object, otherwise
    False
    """

    # Construct Body= parameter
    if isinstance(src_data, bytes):
        object_data = src_data
    elif isinstance(src_data, str):
        try:
            object_data = open(src_data, 'rb')
            # possible FileNotFoundError/IOError exception
        except Exception as e:
            logging.error(e)
            return False
    else:
        logging.error('Type of ' + str(type(src_data)) +
                      ' for the argument \'src_data\' is not supported.')
        return False

    # Put the object
    s3 = boto3.client('s3')
    try:
        s3.put_object(Bucket=dest_bucket_name, Key=dest_object_name, Body=object_data)
    except ClientError as e:
        # AllAccessDisabled error == bucket not found
        # NoSuchKey or InvalidRequest error == (dest bucket/obj == src bucket/obj)
        logging.error(e)
        return False
    finally:
        if isinstance(src_data, str):
            object_data.close()
    return True


def main():
    """Exercise put_object()"""

    test_bucket_name = 'BUCKET_NAME'
    test_object_name = 'OBJECT_NAME'
    filename = 'file.ext'
    # Alternatively, specify object contents using bytes.
    # filename = b'This is the data to store in the S3 object.'

    # Set up logging
    logging.basicConfig(level=logging.DEBUG,
                        format='%(levelname)s: %(asctime)s: %(message)s')

    # Put the object into the bucket
    success = put_object(test_bucket_name, test_object_name, filename)
    if success:
        logging.info(f'Added {test_object_name} to {test_bucket_name}')


if __name__ == '__main__':
    main()

是否可以将文件从 IDE 放到 S3 存储桶中?

【问题讨论】:

    标签: python-3.x amazon-web-services boto3 cloud9


    【解决方案1】:

    是否可以将文件从 IDE 放到 S3 存储桶中?

    是的。如果你知道它的相对路径,你可以使用常规boto3的方法将文件上传到s3,假设你有访问s3的权限。

    如果您不确定脚本中当前的工作目录是什么,您可以使用

    import os
    
    print(os.getcwd())
    

    显然您可以使用os.getcwd() 来构建脚本的完整路径,例如:

    os.getcwd()/file/to/upload/to/s3.txt
    

    【讨论】:

      猜你喜欢
      • 2020-08-03
      • 2011-09-05
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 2017-06-02
      • 2016-12-02
      相关资源
      最近更新 更多