Home > Mobile >  Overwrite an Excel file in Google Drive using Python
Overwrite an Excel file in Google Drive using Python

Time:11-04

I have a loop which runs through a list of files then uploads them a Google Drive folder. There is a client_secrets.json file in the folder on my computer.

I am able to create new files in the Google Drive folder but I wish to overwrite the existing files, without changing the Google Drive file IDs. Is this possible to do this adapting my code below?

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)

upload_file_list ["a.xlsx", "b.xlsx"]


for upload_file in upload_file_list:
    gfile = drive.CreateFile({'parents': [{'id': [FOLDER ID}]})
    gfile.SetContentFile(upload_file)
    gfile.Upload()
gfile.content.close()

CodePudding user response:

Rather than CreateFile, you need to use update()

service.files().update()

CodePudding user response:

You can use files.update. Here's a sample:

    service = build('drive', 'v3', credentials=creds)

    fileId = "<ID of the file you want to update>"
    body={'name':'New name if needed'}

    # Your local file
    media_body = MediaFileUpload('Your file.xlsx',
                                mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        
    updated_file = service.files().update(
        fileId = fileId,
        body=body,
        media_body = media_body
    ).execute()

    print(F'File ID: {updated_file.get("id")}')

Pretty much use your local file as media_body and add the necessary metadata to body. As explained in the documentation linked above you can modify other fields according to the Files object documentation, which you can add to the body variable.

There's also a sample for the Drive v2 API, though it works a little different. My sample is for Drive v3, which is the current version.

  • Related