pythonでgoogle driveを操作する
pythonでクラウドストレージを色々いじってみたらgoogledriveが一番簡単に操作できたので、紹介します。
準備
・google apiに登録して「クライアントID」、「クライアントシークレット」を取得する。(以下参考) qiita.com ・google apiのライブラリ「google-api-python-client」とそれを使いやすくしてくれるラッパー「PyDrive」をインストール。
pip install google-api-python-client pip install PyDrive
・google apiに認証する情報を記載した「settings.yaml」を作成。api登録時に取得した。「クライアントID」「クライアントシークレット」を記載。
client_config_backend: settings client_config: client_id: <クライアントID> client_secret: <クライアントシークレット> save_credentials: True save_credentials_backend: file save_credentials_file: credentials.json get_refresh_token: True oauth_scope: - https://www.googleapis.com/auth/drive.file - https://www.googleapis.com/auth/drive.install
プログラム
settings.yamlと同階層でイカプログを実行してください。
# -*- coding: utf-8 -*- ################################################################ # メインプログラム ################################################################ from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive ################################################################ # 承認 ################################################################ gauth = GoogleAuth() gauth.LocalWebserverAuth() drive = GoogleDrive(gauth) ################################################################ # サンプル1 ################################################################ # Hello.txtテキストを作成し中身に「Hello」と記載。 file1 = drive.CreateFile({'title': 'Hello.txt'}) file1.SetContentString('Hello') # アップロード file1.Upload() ################################################################ # サンプル2 ################################################################ # 一覧を取得し表示 file_list = drive.ListFile({'q': "'root' in parents"}).GetList() for file1 in file_list: print('title: %s, id: %s' % (file1['title'], file1['id'])) ################################################################ # サンプル3 ################################################################ # 指定したIDのデータを削除 file3 = drive.CreateFile({'id': "1WvL7H71lI-cdeAA0wYUtk7T_K-LytRWZ"}) file3.Delete() ################################################################ # サンプル4 ################################################################ # 指定したIDのデータをダウンロード file3 = drive.CreateFile({'id': "1WvL7H71lI-cdeAA0wYUtk7T_K-LytRWZ"}) file3.GetContentFile('hoge1.txt') ################################################################ # サンプル5 ################################################################ # ローカルにあるdata.txtをアップロード file2 = drive.CreateFile() file2.SetContentFile('data.txt') file2.Upload()
終わり
データのアップ、リスト取得、ダウンロード、デリートのやり方を紹介。
ひとまずこれだけできれば、ファイル操作はなんでもできそう。