How to overwrite a file using Google Drive API with Python?

Eng*_*ain 5 python google-api google-drive-api google-api-python-client

I want to create a simple script which will upload a file to my Drive every 5 minutes using cronjob. This is the code I have so far using the boilerplate code I extracted from different locations (mainly 2: getting started page & create page):

from __future__ import print_function
from apiclient import errors
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaFileUpload

def activateService():
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    return build('drive', 'v3', credentials=creds)

SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly',
          'https://www.googleapis.com/auth/drive.file']

myservice = activateService()

file_metadata = {'name': 'myFile.txt'}
media = MediaFileUpload("myFile.txt", mimetype="text/plain")
file = myservice.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
Run Code Online (Sandbox Code Playgroud)

The above code creates the file successfully in the "root" location, but now how I can make it so that it overwrites the previously created file instead of creating new versions everytime? I think I need to use the update API call (https://developers.google.com/drive/api/v3/reference/files/update) but there's no example code on this documentation page which has brought me to a roadblock. Any help trying to decipher that API page to create Python code would be much appreciated, thank you!

DaI*_*mTo 6

您的代码使用它将每次创建一个新文件。

myservice.files().create
Run Code Online (Sandbox Code Playgroud)

您需要使用文件更新

唯一的区别是您需要传递文件 ID。

file = service.files().update(fileId=file_id, media_body=media_body).execute()
Run Code Online (Sandbox Code Playgroud)

  • 除了 https://developers.google.com/drive/api/v3/quickstart/python 之外,没有任何有关 python 和 google Drive 的文档。我刚刚使用这些 API 十年了,我知道这些库是如何工作的。我与你分享我的想法。 (2认同)
  • >> “使用这些 API 已经有十年了,我知道这些库是如何工作的。我与你分享我的想法。” <<哇太棒了,尊重!再次感谢。 (2认同)