Skip to content

Instantly share code, notes, and snippets.

@mjlavin80
Created November 3, 2020 23:20
Show Gist options
  • Save mjlavin80/a642e46a4336a3978c5ab53e076e1016 to your computer and use it in GitHub Desktop.
Save mjlavin80/a642e46a4336a3978c5ab53e076e1016 to your computer and use it in GitHub Desktop.
# You can place these lines of code in a colab notebook to login to Github, and create or load a Google drive file.
# Running this authentication cell will print a message with a hyperlink and a text cell
# visit the link, sign into google, copy the generated authentication code, paste the code in the generated text cell above, and press 'enter'.
# this will link the Colab notebook to your Google drive.
from google.colab import drive
drive.mount('drive')
# save data frame as csv file with google.colab.drive
import pandas as pd
df = pd.DataFrame(some_data)
df.to_csv('data.csv')
# use exclam to execute bash command
!cp data.csv "drive/My Drive/"
# list all csv files in your google drive colab folder
import glob
data_files = glob.glob("/content/drive/My Drive/Colab Notebooks/*.csv")
# see https://colab.research.google.com/drive/1cMmtzM7rYc-cpW0fkRiTRb-ySr2UHf1h for more examples
# Using pydrive to load files from your own Google drive or a public file in someone else's drive
# import dependencies
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.
# You will have to authorize the app, same as above
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# run after authenticating
# Auto-iterate through all files that matches the query ... any file in root folder of your Google Drive, not in the trash
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
print('title: %s, id: %s' % (file1['title'], file1['id']))
id1 = "somegoogledrivefileid"
downloaded = drive.CreateFile({'id':id1})
downloaded.GetContentFile('filename')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment