Skip to content

Instantly share code, notes, and snippets.

@elyase
Created November 16, 2015 02:10
Show Gist options
  • Save elyase/8cb0d2dc33128b7166b1 to your computer and use it in GitHub Desktop.
Save elyase/8cb0d2dc33128b7166b1 to your computer and use it in GitHub Desktop.
Recursively deleting a folder in Dropbox to overcome the 10000 files limitation.
# Include the Dropbox SDK
import dropbox
# Get your app key and secret from the Dropbox developer website
# https://www.dropbox.com/developers-v1/apps
app_key = 'key'
app_secret = 'secret'
flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
# Have the user sign in and authorize this token
authorize_url = flow.start()
print ('1. Go to: ' + authorize_url)
print ('2. Click "Allow" (you might have to log in first)')
print ('3. Copy the authorization code.')
# code = input("Enter the authorization code here: ").strip()
code = 'your_code'
# This will fail if the user enters an invalid authorization code
access_token, user_id = flow.finish(code)
client = dropbox.client.DropboxClient(access_token)
print( 'linked account: ', client.account_info())
# list some files, this will have to be done recursively
# until there are not more files
def get_files(client, path):
"""Get all files at a given path"""
metadata = client.metadata(path, file_limit=20000)
return [item['path'] for item in metadata['contents'] if not item['is_dir']]
def get_folders(client, path):
"""Get all folders at a given path"""
metadata = client.metadata(path, file_limit=20000)
return [item['path'] for item in metadata['contents'] if item['is_dir']]
def delete_files(client, files):
"""Delete all files (not folders) in a given path"""
for file in files:
print('Deletig file', file)
client.file_delete(file)
def recursive_delete(client, start_folder):
try:
print('Trying to delete', start_folder)
client.file_delete(start_folder)
print('Sucess')
return None
except dropbox.rest.ErrorResponse as e:
if e.status == 406:
print('Too many objects, attempting recursive strategy.')
files = get_files(client, start_folder)
print('First deleting {} files'.format(len(files)))
delete_files(client, files)
folders = get_folders(client, start_folder)
print('Now trying to delete {} folders'.format(len(folders)))
for folder in folders:
print('Trying to delete', folder)
recursive_delete(client, folder)
# now that the folder is empty try again
print('Now that {} is empty lets delete it'.format(start_folder))
client.file_delete(start_folder)
else:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment