Search code examples
pythonpython-3.xdownloaddropboxmp4

Download all .mp4 files present in a Dropbox folder


Downloading a file from Dropbox using the API it's straightforward once having the Access Token.

Then, using the method sharing_get_shared_link_file one can simply run

import dropbox
dbx = dropbox.Dropbox("ACCESS_TOKEN")
#dbx.users_get_current_account()
with open("test1.mp4", "wb") as f:
    metadata, res = dbx.sharing_get_shared_link_file("https://www.dropbox.com/s/kowz06jo7i3xyv2/you_saved_me.mp4?dl=0")
    f.write(res.content)

As you can see in the URL, /s/ means that we're dealing with one file.

Thing is, sometimes it's not one file but a folder where the file resides and so the link will include /sh/ instead.

How could I download all the .mp4 files present in a specific folder one by one (without .zip)?

For reference, created a folder with three .mp4 files in it - https://www.dropbox.com/sh/r85vzhq0xxa146s/AAASRlyR-C9ITAd0Cww0Sr9Za?dl=0

Dropbox folder with multiple .mp4 files in it


Solution

  • If you have a shared link to a folder containing files, instead of just a shared link to a specific file, you can use files_list_folder and files_list_folder_continue to list the contents of that folder. You can do so by passing in the URL in the shared_link parameter for files_list_folder.

    The result will contain information about the contents, such as the name of each one.

    You can then use that to build the path to pass to sharing_get_shared_link_file to download each desired file.

    That would look something like this, based on your existing code and URL:

    import dropbox
    
    dbx = dropbox.Dropbox("ACCESS_TOKEN")
    
    shared_link = dropbox.files.SharedLink(url="https://www.dropbox.com/sh/r85vzhq0xxa146s/AAASRlyR-C9ITAd0Cww0Sr9Za?dl=0")
    
    listing = dbx.files_list_folder(path="", shared_link=shared_link)
    # todo: add implementation for files_list_folder_continue
    
    for entry in listing.entries:
        if entry.name.endswith(".mp4"):
            with open(entry.name, "wb") as f:
                # note: this simple implementation only works for files in the root of the folder
                metadata, res = dbx.sharing_get_shared_link_file(url=shared_link.url, path="/" + entry.name)
                f.write(res.content)