dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

python で Google Cloud Storage 上のデータをダウンロードする方法

2020-08-29 17:16:59 | python
python で Google Cloud Storage 上のデータをダウンロードする方法のメモ。

まず、pip install で Google Cloud Storage のライブラリをインストールします。
pip install google-cloud-storage


以下、Google Cloud Storage 上のデータを文字列に格納する方法です。
インメモリのバイトストリームの io.BytesIO オブジェクトにデータを保存し、
そこからバイナリデータを読み込んで文字列として取得します。
import sys
import io
import json
from google.cloud import storage

path = 'gs://~'
client = storage.Client()

buf = io.BytesIO()
client.download_blob_to_file(path, buf)
str = buf.getvalue().decode('utf-8')
buf.close()

print(str)