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()
I believe your goal is as follows.
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.
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)
file_id
on Google Drive is overwritten with the local XLSX file.gauth
.