# Install the PyDrive wrapper & import libraries.
# This only needs to be done once in a notebook.
!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.
# This only needs to be done once in a notebook.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# Create & upload a file.
uploaded = drive.CreateFile({'title': 'filename.csv'})
uploaded.SetContentFile('filename.csv')
uploaded.Upload()
print('Uploaded file with ID {}'.format(uploaded.get('id')))
Here's an extensive tutorial on how to work with files in Google Colab.
If you just want to save your data as csv and download it locally:
from google.colab import files
# e.g. save pandas output as csv
dataframe.to_csv('example.csv')
# or any other file as usual
# with open('example.csv', 'w') as f:
# f.write('your strings here')
files.download('example.csv')
Use View > Table of contents to show the sidebar then click the Files tab. Right-click the file and select Download.
Note: the process is unusual in that the download progress is not shown in the usual way in the browser. Instead it is shown by an orange circle next to the file in Colab. Only when the download is complete does it appear in the browser downloads.
In Firefox, it's best to keep the tab in the foreground while the download is in progress as otherwise it can fail.
from google.colab import files
files.download('file.txt')
If you are using firefox, then this might not work.
For making this work:
from google.colab import files
In next cell, print anything, like print('foo').
After it has printed, erase the print line and replace it with: files.download('file.txt')
Now, it will download. This is a hacky solution told by me colleague. I don't know why it works! If you know why, please comment it.
There is a more cleaner and easier way to do this which works in both firefox and chrome.
Click on > icon. Click on files. It will display all the files and folders in your notebook. Left click on the file you want to download, choose download and you are good to go. This procedure can also be applied to upload file/folder. For uploading folder, you would have to zip it first though.
Mount google drive - follow instructions output on your screen:
from google.colab import drive
drive.mount('/content/drive')
After this step you'll see extra folder in your sidebar file manager named drive
Copy files either by drag and drop method using sidebar, or with this command (note, need to make sure that the specified folder structure exists on the mounted drive):
You can use the same command to move files from Google Drive to notebook environment too, which is a convenient way to backup state in case of runtime disconnects.