python-3.x - 如何使用 python 替换 Google Drive 文件的内容?
问题描述
我有一个 Google Drive 文件,该文件具有其他人依赖的特定文件 ID,以便他们可以打开它。我需要用 python 中的新内容替换这个文件(一个 CSV 文件)的内容。不过,我似乎找不到任何如何做到这一点的例子。我正在使用 Google Drive API v3 (googleapiclient)。请帮忙。
解决方案
我设法创建了一个成功的测试。我在 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 才能正常工作。我只是按照弹出的错误消息来启用所有这些。我希望这对其他人有帮助。
推荐阅读
- ruby-on-rails - 解析请求参数时出错。- 导轨 API
- google-chrome - 在 Google 缓存中,没有图像显示
- reactjs - react-big-calendar 自定义时隙
- passwords - 如何使用 CF 和 LF 为消息事件添加换行符?必须在生成密码重置数据的 CFG 中进行此更改
- apostrophe-cms - 如何确保 slug 不包含重音字符?
- c++ - OpenGL:如何检查光的状态?
- javascript - 工作代码不会在 .load() 之后执行,但会执行其他代码?
- java - JUnit 测试在 GitHub Actions 上失败,但在本地失败 [已解决]
- python - 如何在 Django 中找到 Min(Sum(annotated column))
- docker - 使用 Eureka 和 Docker Swarm 的 Spring Boot Admin