欢迎访问宙启技术站
智能推送

Python中如何使用S3Connection()下载S3存储桶中的文件

发布时间:2024-01-16 16:19:33

在Python中可以使用boto3库来访问和操作Amazon S3存储桶中的文件。首先需要在代码中导入必要的模块和函数:

import boto3
from botocore.exceptions import NoCredentialsError

接下来,我们需要创建一个S3连接:

def create_s3_connection():
    """
    创建S3连接
    """
    access_key = 'YOUR_ACCESS_KEY'
    secret_key = 'YOUR_SECRET_KEY'
    try:
        s3_connection = boto3.client(
            's3',
            aws_access_key_id=access_key,
            aws_secret_access_key=secret_key
        )
        return s3_connection
    except NoCredentialsError:
        print('No AWS credentials found')
        return None

在创建连接时,需要替换YOUR_ACCESS_KEY和YOUR_SECRET_KEY为相应的访问密钥。

接下来,我们可以使用S3连接下载存储桶中的文件。使用download_file()函数可以直接下载文件到本地:

def download_file_from_s3(s3_connection, bucket_name, file_name, local_path):
    """
    从S3存储桶下载文件
    """
    try:
        s3_connection.download_file(bucket_name, file_name, local_path)
        print(f'Successfully downloaded file {file_name} to {local_path}')
    except NoCredentialsError:
        print('No AWS credentials found')
    except Exception as e:
        print(f'Error downloading file: {str(e)}')

使用时,需要提供一个有效的S3连接、存储桶名称、文件名以及下载到本地的路径。

下面是一个完整的使用例子,在此示例中,我们将连接到名为'sample-bucket'的存储桶,并下载名为'sample-file.txt'的文件到本地'/path/to/download/sample-file.txt'路径:

def main():
    s3_connection = create_s3_connection()
    
    if s3_connection is not None:
        bucket_name = 'sample-bucket'
        file_name = 'sample-file.txt'
        local_path = '/path/to/download/sample-file.txt'
        download_file_from_s3(s3_connection, bucket_name, file_name, local_path)
        
if __name__ == '__main__':
    main()

以上代码中,我们首先创建了S3连接,然后使用该连接下载了指定的文件。