LoginSignup
1
2

More than 5 years have passed since last update.

Python で S3 に保存されているファイルの種類を調べる方法

Last updated at Posted at 2015-11-09

S3 へのアクセスは boto3 というライブラリを使う。
ファイルの種類は libmagic を使って mime-type 形式で取得する。

まずは、ライブラリ群のインストール:

$ brew install libmagic
$ pip install python-magic
$ pip install boto3

次にスクリプト:

# 対象ファイルのパスのプレフィックス
key_prefix = 'uploads/'

# 対象ファイル名のパターン
key_pattern = 'uploads/\d+/images/.*'

# ダウンロード用の一時ファイル名
temporary_filename = '/tmp/downloaded_file'

for s3_object in bucket.objects.filter(Prefix=key_prefix):
    if not re.match(key_pattern, s3_object.key):
      continue
    s3_object.Object().download_file(temporary_filename)
    mime_type = magic.from_file(temporary_filename, mime=True)
    print("{}: {}".format(s3_object.key, mime_type)
1
2
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
1
2