LoginSignup
0
0

More than 1 year has passed since last update.

Python boto3でAWS S3を操作しよう

Last updated at Posted at 2022-02-04

はじめに

Python boto3でAWS S3へのバケット作成やデータアップロードなどjupyter notebookにて行います。

まずはboto3をインポート
import boto3

インストールできていない場合は pip install boto3 でインストール。

S3へのアクセスを可能にします
client = boto3.client('s3',
                      region_name='ap-northeast-1',
                      aws_access_key_id = 'ご自身のkey_id',
                      aws_secret_access_key = 'ご自身のaccess_key')

ec2を操作したい場合は's3'の部分をec2にするとec2の操作が可能になります。
region_nameは東京であれば'ap-northeast-1'でokです。

access_key_idやsecret_access_keyがわからない場合はターミナルで下記を打つと確認できます。

aws configure get aws_access_key_id
aws configure get aws_secret_access_key

S3へバケットの作成

client.create_bucket(Bucket='任意のバケット名', 
                     CreateBucketConfiguration={'LocationConstraint': 'ap-northeast-1'})

これでS3上にバケットを作成することができます。
ちなみにCreateBucketConfiguration={'LocationConstraint': 'ap-northeast-1'}は必須でこれがないと以下のエラーが発生します。
ClientError: An error occurred (IllegalLocationConstraintException) when calling the CreateBucket operation: The unspecified location constraint is incompatible for the region specific endpoint this request was sent to.

S3上の不要バケット削除方法

client.delete_bucket(Bucket='任意のバケット名')

バケット内にデータが存在するとバケットの削除はできません。

ローカルデータをS3上の指定したバケットにアップする方法

def upload_files(file_name, bucket, object_name=None, args=None):
    """
    file_name: name of file on local computer
    bucket: bucket name
    object_name: name of file on s3
    args: custom srgs
    """

    if object_name is None:
        object_name = file_name

    response = client.upload_file(file_name, bucket, object_name, ExtraArgs=args)

    print(response)


upload_files('data/kari.txt', 'バケット名')

上記upload_files関数の引数にアップしたいデータのパス、空のバケット名を入れることでローカルからS3の空バケットにデータをアップすることが可能です。

S3上のバケット内に複数のデータをアップしたい場合

import glob

files = glob.glob('data/*')
files
#'data/kari3.csv', 'data/kari2.txt', 'data/kari.txt'が表示されます
#globを使用しローカルのdataフォルダ直下のデータをfilesに格納します。

for file in files:
    upload_files(file, 'バケット名')
    print('uploaded', file)

for文を使いローカルにあるdataフォルダ直下の全てのデータをS3へアップロードができます。

S3上のバケットからローカルへデータをダウンロードする方法

s3 = boto3.resource('s3')
list(s3.buckets.all())
client.list_buckets()
bucket = s3.Bucket('バケット名')
files = list(bucket.objects.all())

for file in files:
    client.download_file('バケット名', file.key, file.key)

ここもfor文を使用しデータをローカルへダウンロードします。

以上でPython boto3を使用してAWS S3へのバケット作成やデータのアップデートができます!

0
0
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
0
0