Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sizhky/f83e6ac2875239302d8ebeaf5ffa118a to your computer and use it in GitHub Desktop.
Save sizhky/f83e6ac2875239302d8ebeaf5ffa118a to your computer and use it in GitHub Desktop.
Google Colab important code snipplets
### Download a file to Local System from Colab
from google.colab import files
with open('example.txt', 'w') as f:
f.write('some content')
files.download('example.txt')
#======================================================================================================
#upload file to Colab from Local System
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
#=======================================================================================================
### Upload file to Colab
# Install the PyDrive wrapper & import libraries.
# This only needs to be done once per 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 per notebook.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# Download a file based on its file ID.
# A file ID looks like: laggVyWshwcyP6kEI-y_W3P8D26sz
file_id = 'REPLACE_WITH_YOUR_FILE_ID'
downloaded = drive.CreateFile({'id': file_id})
downloaded.GetContentFile('my_file.h5')
#simple method
def getFile_from_drive( file_id, name ):
downloaded = drive.CreateFile({'id': file_id})
downloaded.GetContentFile(name)
#======================================================================================================
### upload file to Drive from colab
!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 per notebook.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# Download a file based on its file ID.
uploaded = drive.CreateFile()
uploaded.SetContentFile('my_file.h5')
uploaded.Upload()
print('Uploaded file with ID {}'.format(uploaded.get('id')))
#simple method
def saveFile_to_drive(name):
uploaded = drive.CreateFile()
uploaded.SetContentFile(name)
uploaded.Upload()
print(f"Uploaded {name} with ID {uploaded.get('id')}")
#=======================================================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment