How to delete multiple files at once using Google Drive API

心不动则不痛 提交于 2019-12-19 09:10:13

问题


I'm developing a python script that will upload files to a specific folder in my drive, as I come to notice, the drive api provides an excellent implementation for that, but I did encountered one problem, how do I delete multiple files at once?
I tried grabbing the files I want from the drive and organize their Id's but no luck there... (a snippet below)

dir_id = "my folder Id"
file_id = "avoid deleting this file"

dFiles = []
query = ""

#will return a list of all the files in the folder
children = service.files().list(q="'"+dir_id+"' in parents").execute()

for i in children["items"]:
    print "appending "+i["title"]

    if i["id"] != file_id: 
        #two format options I tried..

        dFiles.append(i["id"]) # will show as array of id's ["id1","id2"...]  
        query +=i["id"]+", " #will show in this format "id1, id2,..."

query = query[:-2] #to remove the finished ',' in the string

#tried both the query and str(dFiles) as arg but no luck...
service.files().delete(fileId=query).execute() 

Is it possible to delete selected files (I don't see why it wouldn't be possible, after all, it's a basic operation)?

Thanks in advance!


回答1:


You can batch multiple Drive API requests together. Something like this should work using the Python API Client Library:

def delete_file(request_id, response, exception):
  if exception is not None:
    # Do something with the exception
    pass
  else:
    # Do something with the response
    pass

batch = service.new_batch_http_request(callback=delete_file)

for file in children["items"]:
  batch.add(service.files().delete(fileId=file["id"]))

batch.execute(http=http)



回答2:


If you delete or trash a folder, it will recursively delete/trash all of the files contained in that folder. Therefore, your code can be vastly simplified:

dir_id = "my folder Id"
file_id = "avoid deleting this file"

service.files().update(fileId=file_id, addParents="root", removeParents=dir_id).execute()
service.files().delete(fileId=dir_id).execute()

This will first move the file you want to keep out of the folder (and into "My Drive") and then delete the folder.

Beware: if you call delete() instead of trash(), the folder and all the files within it will be permanently deleted and there is no way to recover them! So be very careful when using this method with a folder...




回答3:


Files: delete Permanently deletes a file by ID.

Parameters

fileId The ID of the file to delete.

File.delete deletes a file as in one file at a time if you want to delete more then one you have to send a call for each file you want to delete



来源:https://stackoverflow.com/questions/33692184/how-to-delete-multiple-files-at-once-using-google-drive-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!