简体   繁体   中英

How to delete multiple files at once using Google Drive API

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!

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...

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)

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

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