Skip to content Skip to sidebar Skip to footer

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

Solution 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)

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


Post a Comment for "How To Delete Multiple Files At Once Using Google Drive API"