LoginSignup
6
7

More than 5 years have passed since last update.

PythonでGoogle ColaboratoryとGoogle Driveのファイルのやりとりする(3)

Posted at

4.queryの実行によるidの取得

下準備
説明の便宜上、Google DriveのフォルダColab Notebooks下に
from_colab, to_colabを作成し、to_colab下にgdrive.ipynbをコピーしました。(gdrive_test.ipynb)
なお、この後ファイル名やフォルダ名で検索をするので、もし同じ名前のフォルダやファイルがある場合は、違う名前のフォルダやファイルを作成してください。

drive_disp1.png

drive_disp2.png

下記のスクリプトを作成することでクエリが使用できます。
(リンク先のスクリプトに若干の修正を加えています。)
関数内のパラメータであるqueryにデフォルトで画像ファイルを検索するクエリ("mimeType='image/jpeg'")が入っているので、
gquery(service)を実行すると、Google Drive内の画像ファイルが出力されます。
また、リンク先に他のクエリのパターンについても記載されているのでご確認ください。
https://developers.google.com/drive/v3/web/search-parameters

gquery
def gquery(service,query="mimeType='image/jpeg'"):
    page_token = None
    gquery=[]
    cnt=0
    while True:
        response = service.files().list(q=query,spaces='drive',fields='nextPageToken, \
        files(id, name)',pageToken=page_token).execute()
        for file in response.get('files', []):
            # Process change
            print ('Found file: %s (%s)' % (file.get('name'), file.get('id')))
            gquery.append([cnt,file.get('name'), file.get('id')]) 
            cnt=cnt+1
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break
    return gquery

gdrive_test.ipynbのidを取得したいので、下記のコードにより、
ファイルのidを取得します。id1[2]がダウンロードするファイル'gdrive_test.ipynb'、id2[2]がアップロード先のフォルダ'from_colab'を検索するクエリです。

print_id1
id1=gquery(service,"name='gdrive_test.ipynb'")[0]
print(id1)
print("id1 is following:")
print(id1[2])
print_id2
id2=gquery(service,"name='from_colab'")[0]
print(id2)
print("id2 is following:")
print(id2[2])

5.Goole Driveからのファイルのダウンロード、アップロード

Google Driveからファイルをダウンロードする先として、フォルダtestを作成します。

mkdir
! mkdir test
dir
! dir

下記のコードにより、ダウンロードを実行します。

gdownload
import io
from apiclient.http import MediaIoBaseDownload
def gdownload(service,id,path='./'):    
    fname=service.files().get(fileId=id).execute()["name"]
    request = service.files().get_media(fileId=id)
    fh = io.FileIO(path+fname,'wb')
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print ("Download %d%%." % int(status.progress() * 100))
download
gdownload(service,id1[2],'./test/')

下記のコマンドでダウンロードされていることを確認します。

dir/test
! dir ./test

このファイルを今度はGoogle Driveのfrom_colabフォルダアップロードして、
ファイルをGoogle Driveにアップロードしたファイルを確認することで、ダウンロードとアップロードが成功したことを確認します。

gupload
import os
from apiclient.http import MediaFileUpload
#file upload
def gupload(service,filepath,id=[]):
    file_metadata = {'name': os.path.basename(filepath),'parents':[id]}
    media_body = MediaFileUpload(filepath,chunksize=1024*1024, resumable=True)
    file = service.files().create(body=file_metadata,media_body=media_body).execute()
    print('done')
upload
gupload(service,'./test/gdrive_test.ipynb',id2[2])

6.GitHubを利用した方法

最後に、今までのコードをgutil.pyとしてGitHubにアップロードしました。
git cloneを使って、今までのコードが下記の通り実行できます。

git_clone
! git clone https://github.com/hrnckmr/gutil
import
from gutil import gutil
file_upload_dialog
import google.colab.files as ggl
fname=ggl.upload()
print(fname)
print_name
fname = [k for k in fname.keys()][0]
print(fname)
change_the_json_name
import os
os.rename(fname,'client_secret.json')
service
service = gutil.service()
query1
id1=gutil.gquery(service,"name='gdrive_test.ipynb'")[0]
print(id1)
print("id1 is following:")
print(id1[2])
query2
id2=gutil.gquery(service,"name='from_colab'")[0]
print(id2)
print("id2 is following:")
print(id2[2])
mkdir
! mkdir test
download
gutil.gdownload(service,id1[2],'./test/')
upload
gutil.gupload(service,'./test/gdrive_test.ipynb',id2[2])
6
7
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
6
7