0

I am trying to replace an existing file with the same id in the google drive.

import json
import requests
headers = {"Authorization": "Bearer Token"}
para = {
    "name": "video1.mp4",
}
files = {
    'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
    'file': open("./video1.mp4", "rb")
}
r = requests.post(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
    headers=headers,
    files=files
)
print(r.text)

It creates files of similar names with different id with this code. Can I replace an existing file with the same id by mentioning it somewhere in this code?

1 Answer 1

1

Although I'm not sure whether I could correctly understand Can I replace an existing file with the same id by mentioning it somewhere in this code?, if you want to update an existing file on Google Drive, how about the following modified script?

From your showing script, I understood that you wanted to achieve your goal using requests instead of googleapis for python.

Modified script 1:

If you want to update both the file content and file metadata, how about the following modification?

import json
import requests

fileId = "###" # Please set the file ID you want to update.
headers = {"Authorization": "Bearer Token"}
para = {"name": "video1.mp4"}
files = {
    "data": ("metadata", json.dumps(para), "application/json; charset=UTF-8"),
    "file": open("./video1.mp4", "rb"),
}
r = requests.patch("https://www.googleapis.com/upload/drive/v3/files/" + fileId + "?uploadType=multipart",
    headers=headers,
    files=files,
)
print(r.text)
  • If you want to update only the file content, please modify para = {"name": "video1.mp4"} to para = {}.

Modified script 2:

If you want to update only the file metadata, how about the following modification?

import json
import requests

fileId = "###" # Please set the file ID you want to update.
headers = {"Authorization": "Bearer Token"}
para = {"name": "Updated filename video1.mp4"}
r = requests.patch(
    "https://www.googleapis.com/drive/v3/files/" + fileId,
    headers=headers,
    data=json.dumps(para),
)
print(r.text)

Note:

  • In this answer, it supposes that your access token can be used for upload and update the file. Please be careful about this.

Reference:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.