简体   繁体   English

PyDrive:创建一个Google Doc文件

[英]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. 我正在使用PyDrive在Google云端硬盘中创建文件,但是在使用实际的Google Doc类型项目时遇到了麻烦。

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: 如果我将模仿类型更改为text/plain ,则可以正常工作,但它却给我以下错误:

raise ApiRequestError(error) pydrive.files.ApiRequestError: https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&alt=json returned "Invalid mime type provided"> 引发ApiRequestError(错误)pydrive.files.ApiRequestError:https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&alt=json返回“提供了无效的mime类型“>

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. 如果我将MimeType保持原样,但删除对SetContentString的调用,它也可以正常工作,因此看来这两种情况不能很好地配合使用。

What is the proper way to create a Google Doc and set the content? 创建Google文档和设置内容的正确方法是什么?

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. 可以通过Google笔记本访问此文件。 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. 可以使用Google文档打开。 List of supported formats and corresponding mime types can be found here . 可以在此处找到支持的格式和相应的mime类型的列表。

To convert file on the fly to Google Docs format, use: 要将文件即时转换为Google Docs格式,请使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM