LoginSignup
12
14

More than 1 year has passed since last update.

Google colaboでGoogle DriveのファイルをPythonで操作する

Last updated at Posted at 2019-03-18

はじめに

Googleドライブへのマウント方法ですが、現在はより簡単になりました。
▼下記の記事で紹介しているのでこちらをご確認いただいた方が良いかと思います。

Google colabにGoogleドライブをマウントする

Google Colaboratoryを使う場合、GoogleDriveをマウントするとGoogleDriveに読み書きできるので便利です。

#1.Google Driveをマウントする


# カレントディレクトリのファイル一覧をみてみます。
import os
os.listdir()
>>['.config', 'sample_data']
# Googleドライブをcontentというマウントポイントにマウントします。MP名はなんでもOKです。
from google.colab import drive
drive.mount(mountpoint="content")

# リンク先に行けと言われるのリンクをクリックします。
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?うんたらかんたら

# リンク先でGETした認証コードをペーストしてエンターします。
Enter your authorization code:
ここにテキストボックスでてくるのでのリンク先で取得したキーを入力してエンター
··········
# マウントできたみたいです!
Mounted at content

# もう一回カレントディレクトリのファイル一覧を確認すると・・・
os.listdir()

# 新しく"content"フォルダが存在しています!
# このフォルダ配下にGoogleドライブのファイルが存在しているはずです。
>>['.config', 'content', 'sample_data']

# 念のためcontentフォルダの中身一覧もみてみます。
os.chdir("content")
os.listdir()
>>['My Drive', '.Trash']

os.chdir("My Drive")
os.listdir()

# 下記のようにきちんとドライブ内のファイルが見れました。
>>['Google フォト',
 'climbing_preparation_list1.xlsx.gsheet',
 'NoteMaster Sync',
 'Google フォト (1)',
 'Dropbox.7z',
 'Google Document 2010',
 '00_仕事',
 'jplus_folder',
 'ToDo.gsheet',
 'Python_検索結果.gsheet',
 'MySite.gscript',
 'Lavo Site.gscript',
 'GmaiAttached',
 '[GAS]GoogleAppsScript 作業フォルダ',
 'GmailからGoogleドライブ.gscript',
 '不要メールリスト作成.gscript',
 'URL作成.gscript',
 'LINE Bot 2nd.gscript',
 'カレンダーを操作します.gscript']

#2. ファイル操作してみます。

これでGoogle Driveのcsvファイルをcolabからpandasで読み込んだりできます。
これで本題のGoogle Driveのファイルをまとめて操作できます。
下記は、GASファイル(.gscript)をまとめてリネームした例です。

gscript拡張子のファイルを抽出してファイル名の頭にGSとつける。

# まずGASファイルを抽出
for i, j in enumerate(os.listdir()):
  if j[-6 : ] == "script":
    print(i,j)

12 MySite.gscript
13 Lavo Site.gscript
16 GmailからGoogleトライフ.gscript
17 不要メールリスト作成.gscript
18 URL作成.gscript
19 LINE Bot 2nd.gscript
20 カレンターを操作します.gscript
22 無題のフロシェクト.gscript
# リネームしてみる
for i, j in enumerate(os.listdir()):
  if j[-6 : ] == "script":
    os.rename(j , "GS_" + j )
    print(i,j)

# 実際にGoogle Driveで確認したところ出来てました。
12 GS_MySite.gscript
13 GS_Lavo Site.gscript
16 GS_GmailからGoogleトライフ.gscript
17 GS_不要メールリスト作成.gscript
18 GS_URL作成.gscript
19 GS_LINE Bot 2nd.gscript
20 GS_カレンターを操作します.gscript
22 GS_無題のフロシェクト.gscript

おわり

12
14
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
12
14