简体   繁体   中英

Google Drive Update File

from googleapiclient.http import MediaFileUpload
from Google import Create_Service

CLIENT_SECRET_FILE = 'client-secret.json'
API_NAME ='drive'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/drive.file']

service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)

#Upload file
file_metadata = {
    'name': 'image.jpg', # Name to upload to Google Drive
    'parents': ['insert parents here']
}

media_content = MediaFileUpload('image.jpg', mimetype='image/jpg') # image from 
folder

file = service.files().create(
    body = file_metadata,
    media_body = media_content 
).execute()

print(file)

Newbie here, does anyone know how to overwrite a single file uploaded to Google Drive without having to manually replace the file using file Id? Additionally, why Google Drive does not overwrite the file of the same name automatically when uploading file via code above just like when you do it manually? It keeps creating the same file of the same name in Google Drive.

If you want to modify a file's metadata or content, you can simply use files.update , something similar to:

file = service.files().get(fileId=file_id).execute()
media_body = MediaFileUpload(new_filename, mimetype=new_mime_type, resumable=True)
updated_file = service.files().update(fileId=file_id, body=file, newRevision=new_revision, media_body=media_body).execute()

Moreover, bear in mind that Drive UI is different from Drive API meaning that some functionalities might work a little bit different. Drive API works by using file ids so whenever you want to modify a file, you need to specify the fileId , hence the behavior you are observing.

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM