python呼叫aws api操作s3

2021-09-24 13:24:57 字數 2550 閱讀 5729

首先需要配置金鑰和密碼

建立配置資料夾

mkdir ~/.aws

建立配置檔案

vim ~/.aws/config

[default]

output = json #輸出格式

region = ap-northeast-2 #預設區域

建立金鑰檔案

vim ~/.aws/credentials

[default]

aws_access_key_id = *****

aws_secret_access_key = ****

編寫上傳指令碼

vim s3sample.py

#!/usr/bin/python

import logging

import boto3

from botocore.exceptions import clienterror

defupload_file

(file_name, bucket, object_name=

none):

"""upload a file to an s3 bucket

:param file_name: file to upload

:param bucket: bucket to upload to

:param object_name: s3 object name. if not specified then same as file_name

:return: true if file was uploaded, else false

"""# if s3 object_name was not specified, use file_name

if object_name is

none

: object_name = file_name

# upload the file

s3_client = boto3.client(

's3'

)try

: response = s3_client.upload_file(file_name, bucket, object_name)

except clienterror as e:

logging.error(e)

return

false

return

true

defmain()

:"""exercise upload_file()"""

# set these values before running the program

bucket_name =

'test-bucket'

file_name =

'testfile'

object_name =

'testfile'

# set up logging

logging.basicconfig(level=logging.debug,

format

='%(levelname)s: %(asctime)s: %(message)s'

)# upload a file

response = upload_file(file_name, bucket_name, object_name)

if response:

logging.info(

'file was uploaded'

)if __name__ ==

'__main__'

: main(

)

#!/usr/bin/python

import boto3

import botocore

bucket_name =

'test-bucket'

# replace with your bucket name

key =

'testfile'

# replace with your object key

s3 = boto3.resource(

's3'

)try

: s3.bucket(bucket_name)

.download_file(key,

'testfile'

)except botocore.exceptions.clienterror as e:

if e.response[

'error'][

'code']==

"404"

:print

("the object does not exist."

)else

:raise

#上傳

aws s3 cp ./testfile s3://testbucket/

aws s3 cp s3://testbucket/testfile ./

更多python操作示例

pythontxt操作 python文字操作問題

小弟新手請高手們幫忙看一下我的程式的問題。我要實現將乙個文字中的內容稍作轉換寫入到另乙個文字。原文本 a123,b1234,c456789,d987456,a321,b426,c456489,d123456,後面還有好多.小弟新手請高手們幫忙看一下我的程式的問題。我要實現將乙個文字中的內容稍作轉換寫...

python 用python對xml進行操作

首先,我先給出一段xml文件 liechtenstein yes 2 2008 141100 austria direction e switzerland direction w singapore yes 5 2011 59900 malaysia direction n panama yes ...

python的基礎操作 Python基礎操作彙總

變數命名 變數名只能是字母 數字或下劃線的任務組合 變數名的第乙個字元不能是數字 不能使用一些預留的關鍵字,如and,as assert,break,etc.官方推薦明明方式 name of bf python 沒有常量的說法,推薦到全大寫表示常量 字元發展史 ascii gb2312 gbk1.0...