LoginSignup
11
10

More than 1 year has passed since last update.

pythonによるGCSへのバケット・ファイルの操作(転送・取得・削除・読み込み等)まとめ

Last updated at Posted at 2020-05-08

※以下のコードはJupyter Notebookで書いて使用するものとなります。

※GCP、GCSに対する環境構築や設定が行われていることを前提とします。

最初に実行している.py
import os
import pandas as pd
from io import BytesIO
from google.cloud import storage

# ↓my_gcp_credentials.jsonはサービスアカウントから発行している
storage_client  = storage.Client.from_service_account_json('my_gcp_credentials.json')

※上記コードをJupyterで実行した後で以下の操作・コードを実行します。

バケットを作成する

created_bucket.py
created_bucket_name = 'tmp_bucket_qitaqita'

bucket = storage_client.create_bucket(created_bucket_name)

バケット名は世界中で重複のないものとしなければならないので注意。
(当初"tmp_bucket"という名前で作成しようとしましたが、すでに存在しているとのことでエラーとなりました。)

ローカルファイルをバケットへ転送する

trans_to_bucket.py
bucket_name = 'tmp_bucket_qitaqita'
file_name = 'send_txt.txt' #送るものの名前
destination_blob_name = 'sended_txt.txt' #送り先での名前

bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(file_name)

送り先での名前を以下のようにすると、make_dirというディレクトリが作成されその中にファイルが転送されます。
destination_blob_name = 'make_dir/sended_txt_2.txt'

バケット内のファイルを削除する

del_bucket_file.py
bucket_name = 'tmp_bucket_qitaqita'
file_name = 'sended_txt.txt'#バケット内の削除したいファイル名

bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(file_name)
blob.delete()

バケット名一覧を表示する

bucket_name.py
blobs = storage_client.list_buckets()
for blob in blobs:
    print(blob.name)

バケット内のファイル名一覧を表示する

filename_in_bucket.py
bucket_name = 'tmp_bucket_qitaqita'

bucket = storage_client.get_bucket(bucket_name)
blobs = bucket.list_blobs()
for blob in blobs:
    print(blob.name)

バケットを削除する

del_bucket.py
bucket_name = 'tmp_bucket_qitaqita'#削除したいバケット名

bucket = storage_client.get_bucket(bucket_name)
bucket.delete()

※バケット内にファイルが何もない場合に実行できます

バケット内にあるtxtファイルを読み込む & ローカルに保存する

読み込み&保存.py
bucket_name = 'tmp_bucket_qitaqita'
file_name = 'sended_txt.txt'#読み込みたいバケット内のファイル名

bucket = storage_client.get_bucket(bucket_name)
blob = storage.Blob(file_name, bucket)

content = blob.download_as_string()
with open('sended_txt.txt', mode='wb') as f:
    f.write(content)

バケット上のcsvファイルをpandasで読み込む

csvファイル読み込む.py
bucket_name = 'tmp_bucket_qitaqita'
file_name = 'dataset_data.csv'

bucket = storage_client.get_bucket(bucket_name)
blob = storage.Blob(file_name, bucket)
content = blob.download_as_string()
df_csv = pd.read_csv(BytesIO(content))

他にも需要がありそうな操作があれば適宜追加します

余談:今回、qiitaへの初投稿となりました。参考になれば嬉しい。

11
10
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
11
10