Search code examples
pythongoogle-drive-apipydrive

PyDrive: Create a Google Doc file


I am using PyDrive to create files in Google Drive, but I'm having trouble with the actual Google Doc type items.

My code is:

file = drive.CreateFile({'title': pagename, 
"parents":  [{"id": folder_id}], 
"mimeType": "application/vnd.google-apps.document"})

file.SetContentString("Hello World")

file.Upload()

This works fine if I change the mimetype to text/plain but as is it gives me the error:

raise ApiRequestError(error) pydrive.files.ApiRequestError: https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&alt=json returned "Invalid mime type provided">

It also works fine if I leave the MimeType as is, but remove the call to SetContentString, so it appears those two things don't behave well together.

What is the proper way to create a Google Doc and set the content?


Solution

  • Mime type must match the uploaded file format. You need a file in one of supported formats and you need to upload it with matching content type. So, either:

    file = drive.CreateFile({'title': 'TestFile.txt', 'mimeType': 'text/plan'})
    file.SetContentString("Hello World")
    file.Upload()
    

    This file can be accessed via Google Notebook. Or,

    file = drive.CreateFile({'title': 'TestFile.doc', 
                             'mimeType': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'})
    file.SetContentFile("TestFile.docx")
    file.Upload()
    

    which can be opened with Google Docs. List of supported formats and corresponding mime types can be found here.

    To convert file on the fly to Google Docs format, use:

    file.Upload(param={'convert': True})