[英]How do I replace the contents of a Google Drive file using python?
I have a Google Drive file that has a specific file id that others rely on so they can open it. 我有一个Google云端硬盘文件,该文件具有其他人依赖的特定文件ID,以便他们可以打开它。 I need to replace the contents of this file (a CSV file) with new content within python.
我需要用python中的新内容替换此文件(CSV文件)的内容。 I can't seem to find any examples of how to do this, though.
不过,我似乎找不到任何执行此操作的示例。 I'm using Google Drive API v3 (googleapiclient).
我正在使用Google Drive API v3(googleapiclient)。 Please help.
请帮忙。
I managed to create a successful test. 我设法创建了一个成功的测试。 I created a file (test.txt) in Google drive with some basic text in it.
我在Google驱动器中创建了一个文件(test.txt),其中包含一些基本文本。 I obtained the file id by sharing a link and extracting the id from the link and then unshared it again.
我通过共享链接并从链接中提取ID来获取文件ID,然后再次取消共享。 This python code successfully replaced the text in that file with the text in _textStream.
此python代码成功用_textStream中的文本替换了该文件中的文本。 My ultimate goal of replacing the CSV information is achieved similarly, except that the BytesIO object will be the CSV data and the _mimeType will be 'text/csv':
除了替换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()
The Google API documentation sure is opaque and v3 has few examples in python! Google API文档确定是不透明的,并且v3中的python示例很少! Obviously, the Drive API key must be set up and the API enabled for Google Drive for this to work.
显然,必须设置Drive API密钥并启用Google Drive的API才能使其正常工作。 I simply followed the error messages that popped up to enable all of that.
我只是遵循弹出的错误消息来启用所有功能。 I hope this helps someone else.
我希望这可以帮助其他人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.