Skip to content

Instantly share code, notes, and snippets.

@minhntm
Created April 9, 2018 09:27
Show Gist options
  • Save minhntm/6015085c6c5b58f0b47f2573e41d7d6c to your computer and use it in GitHub Desktop.
Save minhntm/6015085c6c5b58f0b47f2573e41d7d6c to your computer and use it in GitHub Desktop.
Access Google Driver by PyDrive
#Install PyDrive
# !pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# PyDrive reference:
# https://googledrive.github.io/PyDrive/docs/build/html/index.html
# Create & upload a file text file.
uploaded = drive.CreateFile({'title': 'Sample upload.txt'})
uploaded.SetContentString('Sample upload file content')
uploaded.Upload()
print('Uploaded file with ID {}'.format(uploaded.get('id')))
# Load a file by ID and print its contents.
downloaded = drive.CreateFile({'id': uploaded.get('id')})
print('Downloaded content "{}"'.format(downloaded.GetContentString()))
# find file
# docs: http://pythonhosted.org/PyDrive/filelist.html
# search params (REST v2): https://developers.google.com/drive/v2/web/search-parameters
file_list = drive.ListFile({'q': "title='ptb.train.txt'"}).GetList()
for file in file_list:
print(file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment