LoginSignup
8

More than 5 years have passed since last update.

boto3でS3のファイルを操作

Last updated at Posted at 2016-01-07

環境

  • mac os x 10.10.5
  • python 3.5.0
  • pip 7.1.2

準備

boto3インストール


$pip install boto3

credentials設定(e.g. ~/.aws/credentials)

[default]
aws_access_key_id = YOUR_KEY
aws_secret_access_key = YOUR_SECRET

地域設定 (e.g. ~/.aws/config):

[default]
region=eu-central-1

アップロード


import boto3

s3_client = boto3.client('s3')

# Upload the file to S3
s3_client.upload_file('test.txt', 'bucket-name', 'test-remote.txt')

情報取得


import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('bucket-name')

for object in bucket.objects.all():
    print(object.key)

古いファイルを削除


import boto3
import datetime as dt

s3 = boto3.resource('s3')
retention_period = 100

bucket = s3.Bucket('bucket-name')

# check each file if it is expired or not
for object in bucket.objects.all():
    gap = dt.datetime.now(dt.timezone.utc) - object.last_modified

    if gap.days > retention_period:
        object.delete()

随時追加していきます。

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
8