2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

boto3 で s3 にアクセス

Last updated at Posted at 2018-03-15

~/.aws/credentials に、
 aws_access_key_id
 aws_secret_access_key
が書かれているとします。

バケットの作成

create_bucket.py
# ! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	create_bucket.py
#
#					Mar/16/2018
# ------------------------------------------------------------------
import	sys
import	boto3

sys.stderr.write("*** 開始 ***\n")

bucket_target = sys.argv[1]
s3 = boto3.client('s3')
s3.create_bucket(Bucket=bucket_target, \
	CreateBucketConfiguration={'LocationConstraint': 'ap-northeast-1'})

sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行コマンド (data-aa というバケットを作成)

./create_bucket.py data-aa

既に、同じ名前のバケットが存在しているとエラーになります。

バケットのリスト

list_buckets.py
# ! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	list_buckets.py
#
#						Mar/16/2018
# ------------------------------------------------------------------
import	sys
import	boto3

sys.stderr.write("*** 開始 ***\n")
s3 = boto3.resource('s3')

for bucket in s3.buckets.all():
	print(bucket.name)
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行コマンド

./list_buckets.py

ファイルのアップロード

upload_data.py
# ! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	upload_data.py
#
#						Mar/16/2018
# ------------------------------------------------------------------
import	sys
import	boto3

sys.stderr.write("*** 開始 ***\n")
bucket_target = sys.argv[1]
file_upload = sys.argv[2]

s3 = boto3.resource('s3')

data = open(file_upload, 'rb')
s3.Bucket(bucket_target).put_object(Key=file_upload, Body=data)

sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行コマンド (data-aa に test.txt をアップロード)

./upload_data.py data-aa test.txt

ファイルの一覧

list_files.py
# ! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	list_files.py
#
#						Mar/16/2018
# ------------------------------------------------------------------
import sys
import boto3

sys.stderr.write("*** 開始 ***\n")

bucket_in = sys.argv[1]

s3 = boto3.resource('s3')

my_bucket = s3.Bucket(bucket_in)
for object in my_bucket.objects.all():
	print(object)

sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行コマンド (data-aa 内の表示)

./list_files.py data-aa
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?