首页 > 解决方案 > 如何使用 python 替换 Google Drive 文件的内容?

问题描述

我有一个 Google Drive 文件,该文件具有其他人依赖的特定文件 ID,以便他们可以打开它。我需要用 python 中的新内容替换这个文件(一个 CSV 文件)的内容。不过,我似乎找不到任何如何做到这一点的例子。我正在使用 Google Drive API v3 (googleapiclient)。请帮忙。

标签: python-3.xgoogle-api-python-client

解决方案


我设法创建了一个成功的测试。我在 Google 驱动器中创建了一个文件 (test.txt),其中包含一些基本文本。我通过共享链接并从链接中提取 id 来获得文件 id,然后再次取消共享。此 python 代码成功地将该文件中的文本替换为 _textStream 中的文本。我替换 CSV 信息的最终目标是类似地实现的,除了 BytesIO 对象将是 CSV 数据并且 _mimeType 将是'text/csv':

from oauth2client import file, client, tools
from googleapiclient.discovery import build
from httplib2 import Http
from io import BytesIO
from apiclient.http import MediaIoBaseUpload

def gauthenticate():
    # If modifying these scopes, delete the file token.json.
    SCOPES = 'https://www.googleapis.com/auth/drive'
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('drive', 'v3', http=creds.authorize(Http()))
    return service

def SaveTxtGDrive(service):
    # Fill in your own file id here:
    fileId = '1kEyXXXXXXXX_gEd6lQq'
    _mimeType = 'text/plain'
    _textStream = BytesIO(b'Here is some arbitrary data\nnew text\nAnother line\n') 
    _media = MediaIoBaseUpload(_textStream, mimetype=_mimeType,
        chunksize=1024*1024, resumable=True)
    _updatedFile = service.files().update(fileId=fileId,
        media_body=_media).execute()

def main():
    _service = gauthenticate()
    SaveTxtGDrive(_service)
    return

if (__name__ == '__main__'):
    main()    

Google API 文档肯定是不透明的,并且 v3 在 python 中几乎没有示例!显然,必须设置 Drive API 密钥并为 Google Drive 启用 API 才能正常工作。我只是按照弹出的错误消息来启用所有这些。我希望这对其他人有帮助。


推荐阅读