Identicon
Identicon

Reputation: 403

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

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()

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!

Upvotes: 5

Views: 4501

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116968

Your code uses which will create a new file every time.

myservice.files().create

You need to use File update

The only diffrence is you need to pass the file id.

file = service.files().update(fileId=file_id, media_body=media_body).execute()

Upvotes: 8

Related Questions