Google Colab | python3Xのブログ

python3Xのブログ

ここでは40代、50代の方が日々の生活で役に立つ情報や私の趣味であるプログラム、Excelや科学に関する内容で投稿する予定です。

Google Colaboratryはよく利用するのですが

その利用方法が書かれているサイトがありましたので

試してみました

 

!pip install gspread

Requirement already satisfied: gspread in /usr/local/lib/python3.6/dist-packages (3.0.1)
Requirement already satisfied: requests>=2.2.1 in /usr/local/lib/python3.6/dist-packages (from gspread) (2.21.0)
Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.2.1->gspread) (2.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.2.1->gspread) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.2.1->gspread) (2019.6.16)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.2.1->gspread) (1.24.3)

from google.colab import auth
from oauth2client.client import GoogleCredentials
import gspread
# 認証処理
auth.authenticate_user()
gc = gspread.authorize(GoogleCredentials.get_application_default())
# 'SpreadsheetSample'というスプレッドシートの先頭ワークシートをオープン
worksheet = gc.open('SpreadsheetSample').get_worksheet(0)
# A1セルに'foo'という値を上書き
worksheet.update_acell('A1', 'foo')
# A2からC3のセルエリアに'bar'を一括で上書き
cell_list = worksheet.range('A2:C3')
for cell in cell_list:
    cell.value = 'bar'
worksheet.update_cells(cell_list)
# A1セルの値を取得し、表示
val = worksheet.acell('A1').value
print(val)
# A1セルを0,0とするようなセル指定で
# 2,2(B2)の位置のセルを取得
val = worksheet.cell(2, 2).value
print(val)
foo
bar
from google.colab import files
with open('sample.txt', 'w') as f:
  f.write('some content')
files.download('sample.txt')
files.upload()
from google.colab import drive
drive.mount('/chapter11/')
Mounted at /chapter11/
import os
if not os.path.exists('/chapter11/My Drive/sample'):
  !mkdir /chapter11/My\ Drive/sample
 
with open('/chapter11/My Drive/sample/sample.txt', 'w') as f:
  for _ in range(0, 3):
    f.write('you can create a new file on google drive. \n')
with open('/chapter11/My Drive/sample/sample.txt', 'a') as f:
  f.write('you can append text.')
with open('/chapter11/My Drive/sample/sample.txt', 'r') as f:
  print(f.read())
you can create a new file on google drive.
you can create a new file on google drive.
you can create a new file on google drive.
you can append text.
!pip install --upgrade --quiet PyDrive
・・・