PyDrive:创建一个 Google 文档文件

PyDrive: Create a Google Doc file

我正在使用 PyDrive 在 Google 驱动器中创建文件,但我在处理实际的 Google 文档类型项目时遇到了问题。

我的代码是:

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

file.SetContentString("Hello World")

file.Upload()

如果我将 mimetype 更改为 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">

如果我将 MimeType 保持原样,但删除对 SetContentString 的调用,它也能正常工作,所以看起来这两个东西在一起时表现不佳。

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

Mime 类型必须与上传的文件格式相匹配。您需要一种受支持格式的文件,并且需要上传具有匹配内容类型的文件。所以,要么:

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

可以通过 Google 笔记本访问此文件。或者,

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

可以用 Google 文档打开。可以找到支持的格式列表和相应的 MIME 类型 here

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

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