I just wondering that is it possible to load local data files(like .xlsx or .csv files that on my google drive) into Colaboratory?
I was a bit confused by the example for loading local files on first glance as there was no place to specify a file path. All you need to do is copy and paste the recipe to figure this out, but to be clear:
from google.colab import files
uploaded = files.upload()
will open an upload dialogue window where you can browse and select your local files for upload.
Then
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
will show you the keys to access what you just uploaded.
Edit for additional clarification: The dictionary uploaded
will have keys of the selected filenames - so if for example you select a file my_test.txt
, then you would access that file using uploaded['my_test.txt']
.
Say, You have a folder on your Google drive named Colab
and a csv
is file located there.
To load this file
import pandas as pd
titanic = pd.read_csv(“drive/Colab/Titanic.csv”)
titanic.head(5)
Before that, you may need to run these command:
Run these codes first in order to install the necessary libraries and perform authorization.
!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse
from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}
When you run the code above, you should see a result like this:
Click the link, copy verification code and paste it to text box.
After completion of the authorization process,
mount your Google Drive:
!mkdir -p drive
!google-drive-ocamlfuse drive
To load local data files to Colab:
Method 1: Google Drive Method
Mount Google drive in Colab
from google.colab import drive
drive.mount('/content/gdrive')
Then-> path = "/gdrive/My Drive/filename"
You can now access google drive files in Google Colab.
Method 2: Direct Load
from google.colab import files
def getLocalFiles():
_files = files.upload()
if len(_files) >0:
for k,v in _files.items():
open(k,'wb').write(v)
getLocalFiles()
Method 3: Using import files
from google.colab import files
uploaded = files.upload()