I believe your goal is as follows.
- You want to update the existing XLSX file with a new XLSX file on Google Drive.
- You want to achieve this using pydrive for python.
Issue and workaround:
When I saw the document of pydrive, I couldn't find the method for updating the file content while the file metadata can be updated. From your showing script, I understand that you already had the access token by the script of pydrive. So, in this answer, using your authorization script, I would like to propose a sample script for updating the file content of the file on Google Drive.
Sample script:
Before you use this script, please set file_id
and uploadXLSXfilename
.
import json
import requests
from pydrive.auth import GoogleAuth
file_id = "###" # Please set the file ID of the existing XLSX file on Google Drive.
uploadXLSXfilename = "./sample.xlsx" # Please set your local XLSX file name with the path.
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
files = {
"data": ("metadata", json.dumps({"mimeType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}), "application/json"),
"file": open(uploadXLSXfilename, "rb"),
}
res = requests.patch(
"https://www.googleapis.com/upload/drive/v3/files/" + file_id + "?uploadType=multipart",
headers={"Authorization": "Bearer " + gauth.attr["credentials"].access_token},
files=files,
)
print(res.text)
- When this script is run, the existing file of
file_id
on Google Drive is overwritten with the local XLSX file.
- And, the access token is used from
gauth
.
Reference: