Google Drive SDK:我想更新文件,而不是创建新文件

Google Drive SDK: I want to update a file, not create new one

在我看来这应该很容易,但由于某些原因我找不到正确的方法:我应该如何使用 [=23= 更新 Google 驱动器中的文件]?

我的代码:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LoadCredentialsFile("mycreds.txt")
drive = GoogleDrive(gauth)
file = drive.CreateFile({'title': 'Hello.txt'})
file.SetContentString('test 1')
file.Upload()

这将创建一个新文件。现在我想在文件中添加下一行 'test 2'。 运行 上面的代码每次都创建新文件,这不是我想要的。

谁能帮我解决这个问题?

爸爸

这是因为您每次 运行 脚本都会调用 CreateFile,因此会创建一个新文档。

如果您想在不关闭脚本的情况下更新文件:

file = drive.CreateFile({'title':'appdata.json', 'mimeType':'application/json'})
file.SetContentString('{"firstname": "John", "lastname": "Smith"}')
file.Upload() # Upload file
file.SetContentString('{"firstname": "Claudio", "lastname": "Afshar"}')
file.Upload() # Update content of the file

我还没有找到通过 ID 获取 GoogleDriveFile 实例的方法,但文档提到遍历与描述匹配的所有文件:

file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file in file_list:
  print 'title: %s, id: %s' % (file['title'], file['id'])

因此,如果您通过搜索文件并检查列表是否只包含一项来使用它,您就会找到您的特定文档。 对于 'q' 的搜索参数:https://developers.google.com/drive/web/search-parameters.

file_list = drive.ListFile({'q': "title='hello.doc' and trashed=false"}).GetList()
if len(file_list) == 1:
    file = file_list.next()
updated_content = file.GetContentString() + "New content"
file.SetContentString(updated_content)
file.Upload()

对不起,我不知道更多细节,如果这对你不起作用,也许看看官方 python Google API: https://developers.google.com/drive/web/quickstart/python

首先,每次使用drive.CreateFile()file.Upload(),都会创建一个新实例。要覆盖同一个文件,您必须指定该文件的文件 ID。 例如,您可以像这样创建一个新文件:

yourfile_id = '*****'
file = drive.CreateFile({'title': 'Hello.txt', 'id': yourfile_id})

这样,您将确保不会有重复的文件。

其次,要更新您的文件,您必须读取它并将要添加的内容附加到读取的数据中。 下面,举个例子:

file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()

for file in file_list:
    if file['title'] == 'Hello.txt':
        new_file = drive.CreateFile({'title': file['title'], 'id': file['id']})
        file_content = new_file.GetContentString()
        file_content = file_content + '\ntest 2'
        new_file.SetContentString(file_content)
        new_file.Upload()

第一行获取根目录中所有文件的列表(您可以通过将 'root' 替换为文件夹 ID 来搜索任何子文件夹) for 循环找到你想要的文件 ('Hello.txt') 并用它的标题和 id 提供 new_file (用旧的替换,如前面提到的那段代码) 接下来两行读取文件内容并附加新数据,最后两行上传并更新文件。