python代码连接s3传输文件
时间: 2024-12-24 13:37:07 浏览: 19
在Python中,你可以使用Boto3库来连接Amazon S3并上传、下载或管理文件。以下是基本步骤:
首先,你需要安装`boto3`库,如果尚未安装,可以通过pip安装:
```bash
pip install boto3
```
然后,通过以下代码设置AWS凭证(通常存储在`.aws`目录下的`credentials`文件或环境变量中):
```python
import boto3
# 使用IAM角色(无凭据)
s3 = boto3.resource('s3')
# 或者使用访问密钥和秘密访问密钥
# aws_access_key_id = 'your-access-key'
# aws_secret_access_key = 'your-secret-key'
# s3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)
```
接下来,你可以使用`resource`对象进行文件操作,如上传文件:
```python
def upload_to_s3(file_path, bucket_name, object_name):
s3.meta.client.upload_file(file_path, bucket_name, object_name)
upload_to_s3('/path/to/local/file.txt', 'your-bucket-name', 'file.txt')
```
同样,下载文件可以用`download_file()`方法:
```python
def download_from_s3(bucket_name, object_name, save_path):
s3.meta.client.download_file(bucket_name, object_name, save_path)
download_from_s3('your-bucket-name', 'file.txt', '/path/to/save/downloaded/file.txt')
```
阅读全文
相关推荐


















