PyDrive:创建一个Google Doc文件

awe*_*r89 4 python google-drive-api pydrive

我正在使用PyDrive在Google云端硬盘中创建文件,但是在使用实际的Google Doc类型项目时遇到了麻烦。

我的代码是:

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

file.SetContentString("Hello World")

file.Upload()
Run Code Online (Sandbox Code Playgroud)

如果我将mimetype更改text/plain为,则可以正常工作,但这样会给我错误:

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

如果我保持MimeType不变,但删除对SetContentString的调用,它也可以正常工作,因此看来这两种情况不能很好地配合使用。

创建Google文档和设置内容的正确方法是什么?

Mac*_*cha 5

哑剧类型必须与上传的文件格式匹配。您需要使用一种受支持的格式的文件,并且需要使用匹配的内容类型上传该文件。因此,要么:

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

可以通过Google笔记本访问此文件。要么,

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

可以使用Google文档打开。可以在此处找到支持的格式和相应的mime类型的列表。

要将文件即时转换为Google Docs格式,请使用:

file.Upload(param={'convert': True})
Run Code Online (Sandbox Code Playgroud)