Skip to content

Instantly share code, notes, and snippets.

@dmn001
Created March 4, 2023 22:35
Show Gist options
  • Save dmn001/ced380b9b8a5a67e4a3395060f958837 to your computer and use it in GitHub Desktop.
Save dmn001/ced380b9b8a5a67e4a3395060f958837 to your computer and use it in GitHub Desktop.
Google Drive batch file deleter
import httplib2
import os
from oauth2client.file import Storage
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from pprint import pprint
# modified from https://medium.com/@staticmukesh/how-i-managed-to-delete-1-billions-files-from-my-google-drive-account-9fdc67e6aaca
def get_credentials():
SCOPES = 'https://www.googleapis.com/auth/drive'
APPLICATION_NAME = 'Drive API Remover'
credential_path = os.path.join(os.getcwd(), 'python_access_token.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store, None)
print('Storing credentials to ' + credential_path)
return credentials
def callback(request_id, response, exception):
if exception:
print("Exception:", exception)
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
resource = service.files()
print(resource)
quit() # uncomment to delete files!!!
while True:
result = resource.list(pageSize=100, fields="files(id, name)").execute()
pprint(result)
if not result:
quit()
files = result['files']
batch = service.new_batch_http_request(callback=callback)
batch_size = min(len(files),99)
print(batch_size)
for i in range(batch_size):
print("deleting %s with id:%s" % (files[0]['name'],files[0]['id']))
batch.add(service.files().delete(
fileId=files[0]['id']
))
del files[0]
batch.execute(http=http)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment