I'm trying to write a pandas.DataFrame
directly to Google Drive, without first writing the file out locally. I can't find a solution and not sure if it is even possible. I've tried the code below, but I get an AttributeError
.
import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)
df = pd.DataFrame({'a':[1,2],'b':[2,3]})
f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(df)
f.Upload()
AttributeError: 'DataFrame' object has no attribute 'encode'
It is possible to get pandas
to write an Excel file directly to a string like:
wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)
file_as_string = save_virtual_workbook(wb)
Here is the above code combined with your example. Please note that this part is untested.
import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)
df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]})
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import save_virtual_workbook
wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)
f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(save_virtual_workbook(wb))
f.Upload()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With