Export dataframe as csv file from google colab to google drive

Athar Noraiz picture Athar Noraiz · Dec 22, 2018 · Viewed 33.2k times · Source

I want to upload a dataframe as csv from colab to google drive.I tried a lot but no luck. I can upload a simple text file but failed to upload a csv.

I tried the following code:

import pandas as pd
df=pd.DataFrame({1:[1,2,3]})
df.to_csv('abc',sep='\t')
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
uploaded = drive.CreateFile({'title': 'sample.csv', 'mimeType':'csv'})
uploaded.SetContentFile('abc')
uploaded.Upload()

Answer

korakot picture korakot · Dec 23, 2018

It may be easier to use mounting instead of pydrive.

from google.colab import drive
drive.mount('drive')

After authentication, you can copy your csv file.

df.to_csv('data.csv')
!cp data.csv "drive/My Drive/"