The best solution I have found for updating a Google drive file is by uploading the file with the ID stated in the drive.CreateFile
function, like you said.
Here is my code for downloading and then overwriting the specific file.
def upload_file_to_drive(file_id, local_path):
"""Overwrites the existing Google drive file."""
update_file = drive.CreateFile({'id': file_id})
update_file.SetContentFile(local_path)
update_file.Upload()
def download_drive_file(file_id, save_path):
"""Downloads an existing Google drive file."""
download_file = drive.CreateFile({'id': file_id})
download_file.GetContentFile(save_path)
In use with an OOP class:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
def get_google_drive_auth(self):
"""Initilaizes the Google drive 'drive' object. """
gauth = GoogleAuth()
# Try to load saved client credentials
gauth.LoadCredentialsFile("path/to/your/credentials/file")
if gauth.credentials is None:
# Authenticate if they're not there
gauth.GetFlow()
gauth.flow.params.update({'access_type': 'offline'})
gauth.flow.params.update({'approval_prompt': 'force'})
gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
else:
# Initialize the saved creds
gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("path/to/your/credentials/file")
self.drive = GoogleDrive(gauth)
def upload_file_to_drive(self, file_id, local_path):
"""Overwrites the existing Google drive file."""
update_file = self.drive.CreateFile({'id': file_id})
update_file.SetContentFile(local_path)
update_file.Upload()
def download_drive_file(self,file_id, save_path):
"""Downloads an existing Google drive file."""
download_file = self.drive.CreateFile({'id': file_id})
download_file.GetContentFile(save_path) # Save Drive file as a local file