googledriveapiv3在python中动态更新文件(使用实时数据)

2024-03-28 11:54:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用一些新数据更新我创建的文件。本质上,我试图将内容附加到已经创建的文件中。我尝试过不同的方法使用不同的属性,但到目前为止似乎没有任何效果。从v2到v3的迁移似乎使python的开发更加困难。在

这是我目前为止的代码

def updateFile(fileID, contents):
    credentials = get_credentials() #this function gets the credentials for oauth
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)
    # First retrieve the file from the API.

    #fileCreated = service.files().get(fileId=fileID).execute()
    #print(dir(fileCreated.update()))
    # File's new content.
    file_metadata = { 'name' : 'notes.txt', 'description' : 'this is a test' }
    fh  = BytesIO(contents.encode())
    media = MediaIoBaseUpload(fh,
                        mimetype='text/plain')
    # Send the request to the API.
    #print(BytesIO(contents.encode()).read())
    print(fileID)
    updated_file = service.files().update(
        body=file_metadata,
        #uploadType = 'media',
        fileId=fileID,
        #fields = fileID,
        media_body=media).execute()

我尝试过使用MediaFileUpload(它只适用于上传文件),但我附加了一个“字符串”,它是使用语音接口实时生成的,不存储在任何文件中。所以我用了mediaobaseupload。在

代码运行时没有任何错误,但文件没有更新。感谢任何帮助。在


Tags: 文件theapihttpgetservicecontentsv3
2条回答

好吧,所以我发现我的代码出了什么问题。显然,我发布的这段代码没有什么问题。我意识到我没有将我创建的文档转换为“google文档”,因此代码没有更新文档。我将我创建的文档的mime类型更改为google文档,现在代码工作正常:)

您还可以使用service.files().get_media(fileId=fileID).execute()获取文件内容并将新内容附加到其中。在

相关问题 更多 >