如何使用python替换Google云端硬盘文件的内容?

时间:2018-11-15 12:53:45

标签: python-3.x google-api-python-client

我有一个Google云端硬盘文件,该文件具有其他人依赖的特定文件ID,以便他们可以打开它。我需要用python中的新内容替换此文件(CSV文件)的内容。不过,我似乎找不到任何执行此操作的示例。我正在使用Google Drive API v3(googleapiclient)。请帮忙。

1 个答案:

答案 0 :(得分:1)

我设法创建了一个成功的测试。我在Google驱动器中创建了一个文件(test.txt),其中包含一些基本文本。我通过共享链接并从链接中提取ID来获取文件ID,然后再次取消共享。此python代码成功用_textStream中的文本替换了该文件中的文本。除了替换BytesIO对象将是CSV数据和_mimeType将是'text / csv'之外,我替换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才能使其正常工作。我只是遵循弹出的错误消息来启用所有功能。我希望这对其他人有帮助。