【问题标题】:PyDrive: Create a Google Doc filePyDrive:创建 Google Doc 文件
【发布时间】:2017-07-31 04:58:28
【问题描述】:

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

我的代码是:

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

file.SetContentString("Hello World")

file.Upload()

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

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

如果我保留 MimeType 原样,它也可以正常工作,但删除对 SetContentString 的调用,所以看起来这两件事不能很好地结合在一起。

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

【问题讨论】:

标签: python google-drive-api pydrive


【解决方案1】:

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

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

可以通过 Google Notebook 访问此文件。或者,

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

可以用谷歌文档打开。支持的格式列表和对应的 mime 类型可以在here找到。

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

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

【讨论】:

  • 这似乎太违反直觉了。为了将 Google Docs 专有格式与 Google Docs API 一起使用,我必须上传不同的格式并转换... 将其作为文本/纯文本,然后将转换命令添加到上传工作,谢谢
猜你喜欢
  • 1970-01-01
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多