Table of Contents [Disable]
Google Sheets にアクセスするためのお作法
Python で Google Sheets にアクセスするには決まりきったお作法がある。
[]内はソースコード内の位置。
- Googleのサービスにアクセスするための service 変数を生成する。[ 2 行目、5 行目]
- 認証情報(ダウンロードした json ファイル名)を設定する。[ 8 行目]
- Google API にログインする。[ 11 行目]
- 共有設定したスプレッドシートキーを変数 SPREADSHEET_KEY に格納する。[ 14 行目]
- 共有設定したスプレッドシートにアクセスする。[ 17 行目]
ソースコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Googleのサービスにアクセスするための service 変数を生成 | |
from oauth2client.service_account import ServiceAccountCredentials | |
# API の記述 | |
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] | |
# 認証情報設定(ダウンロードした json ファイル名を設定) | |
credentials = ServiceAccountCredentials.from_json_keyfile_name('<json ファイル名>', scope) | |
# Google API にログイン | |
gc = gspread.authorize(credentials) | |
# 共有設定したスプレッドシートキーを変数 SPREADSHEET_KEY に格納 | |
SPREADSHEET_KEY = '<スプレッドシートキー>' | |
# 共有設定したスプレッドシートにアクセス | |
ss = gc.open_by_key(SPREADSHEET_KEY) |
関連記事
Python で Google Sheets を操作するための環境設定Photo by Clément H on Unsplash