LoginSignup
28
25

More than 3 years have passed since last update.

【GCP】Google Cloud StorageをPythonで操作する

Last updated at Posted at 2019-12-30

google-cloud-storageのインストール

$ pip install --upgrade google-cloud-storage

ストレージクライアントの作成


from google.cloud import storage
client = storage.Client()

バケットに対する操作

バケットの作成

bucket = storage.Bucket(client)
bucket.name = "test-bucket"
bucket.location = "asia-northeast1"
client.create_bucket(bucket)

バケットの取得

bucket_name = "test-bucket"
bucket = client.get_bucket(bucket_name)

バケットの一覧表示

for bucket in client.list_buckets():
    print(bucket.name)

# test-bucket1
# test-bucket2
# test-bucket3

バケットの存在チェック

print(bucket.exists())

# True

バケットの削除

bucket.delete(force=True)

バケットに対して削除リクエストを送信する場合、バケットは空である必要があります。
パラメータ「force」をTrueにすることで、バケットのオブジェクトを全て削除した上でバケットを削除できます。(Trueで空にする、デフォルトはFalse)
ただし、バケット内のオブジェクトが256個を超える場合、ValueErrorが発生するため、注意が必要です。

バケット内のオブジェクトに対する操作

オブジェクトを一覧表示

for blob in client.list_blobs(bucket_name):
    print(blob.name)

# test_dir/
# test_dir/hoge.txt
# test_dir/test_file_1.txt
# test_dir/test_file_2.txt
# test_file_1.txt
# test_file_2.txt

オブジェクトを一覧表示(Prefix指定)

for blob in client.list_blobs(bucket_name, prefix="test_dir/test"):
    print(blob.name)

# test_dir/test_file_1.txt
# test_dir/test_file_2.txt

オブジェクトのインスタンスを作成

blob = bucket.blob("test_dir/test_file_1.txt") # ストレージのパスを指定

オブジェクトの存在チェック

print(blob.exists())

# True

オブジェクトのダウンロード

blob.download_to_filename("test_file_1.txt") # ダウンロード先のパスを指定

オブジェクトのアップロード

blob.upload_from_filename("test_file_1.txt") # アップロード元のパスを指定

オブジェクトの削除

blob.delete()

参考

google-cloud-storage Library Reference
https://googleapis.dev/python/storage/latest/client.html

28
25
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
28
25