LoginSignup
54
38

More than 3 years have passed since last update.

ColaboratoryからGoogle Driveのファイルを読み書きする

Last updated at Posted at 2018-05-22

こちらの記事 に書いてあるように最近だと

import google.colab.drive
google.colab.drive.mount('gdrive')

とするとgdrive/My Drive以下にグーグルドライブの内容が見えるようになるからそれでやるのが簡単

前書き

Google Colaboratory はGPU付きの仮想計算機上で動く、Tensorflowを含む機械学習関連のライブラリがプレインストールされたPython Jupyter類似のノートブックが使える無料の環境で、最近話題になっている。Colaboratoryとファイルをやりとりする方法はGoogleの公式説明 (Colabノートブック)にあるが、

  • 最も手軽に使えるgoogle.colab.files.download(), google.colab.files.upload()
    • 100MBのやりとりに10分程度かかるほど遅い、
    • Firefoxのバージョンによっては謎のエラー Upload widget is only available when the cell has been executed in the current browser session. Please rerun this cell to enable が出て使えない
  • Google Driveとのファイルやりとりは高速だが公式説明はわかりにくい

という問題点があるので、ColabノートブックからGoogle Driveとファイルをやりとりする簡単なサンプルコードを紹介する。なおColabノートブックにファイルを取り込むだけなら、Linux wgetコマンドで直接ダウンロード出来るところにファイルを置ける場合、Colabノートブックに!wget URLと書くことで高速に取り込むことが出来る。以下のコードはめたはら鵺氏からの助言を参考にした。

必要ライブラリのインポート

import google.colab
import googleapiclient.discovery
import googleapiclient.http

ColaboratoryからGoogle Driveへの認証と接続

毎回必ず実行して下さい。

google.colab.auth.authenticate_user()
drive_service = googleapiclient.discovery.build('drive', 'v3')

Colaboratoryへのファイルの取り込み

変数upload_filenameにGoogle DriveからColaboratoryに取り込みたいファイル名を代入して使う。複数のファイルはzipでまとめて取り込み、Colaboratory上で!unzip ファイル名.zipとして展開すると手間が少ない。

upload_filename = '学習用データ.zip'

file_list = drive_service.files().list(q="name='" + upload_filename + "'").execute().get('files')

# ファイル ID を取得します。
file_id = None
for file in file_list:
  if file.get('name') == upload_filename:
    file_id = file.get('id')
    break

if file_id is None:
  # ファイル ID を取得できなかった場合はエラーメッセージを出力します。
  print(upload_filename + ' が見つかりません.')
else:
  # colab 環境へファイルをアップロードします。
  with open(upload_filename, 'wb') as f:
    request = drive_service.files().get_media(fileId=file_id)
    media = googleapiclient.http.MediaIoBaseDownload(f, request)

    done = False
    while not done:
      progress_status, done = media.next_chunk()
      print(100*progress_status.progress(), end="")
      print("%完了")

  print('GoogleドライブからColab環境へのファイル取り込みが完了しました.')

ColaboratoryからGoogle Driveへのファイル保存

変数saving_filenameに保存したいファイル名を代入して使う。保存したファイルはGoogle Driveのマイドライブに現れる。

saving_filename = "ディープラーニングの学習結果.hdf5"

file_metadata = {
  'name': saving_filename,
  'mimeType': 'application/octet-stream'
}
media = googleapiclient.http.MediaFileUpload(saving_filename, 
                        mimetype='application/octet-stream',
                        resumable=True)
created = drive_service.files().create(body=file_metadata,
                                       media_body=media,
                                       fields='id').execute()
54
38
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
54
38