Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload complete folder to Dropbox using python

I am trying to upload a whole folder to Dropbox at once but I can't seem to get it done is it possible? And even when I am trying to upload a single file I have to precise the file extension in the Dropbox path, is there another way to do it? code I am using

client = dropbox.client.DropboxClient(access_token)
f= open(file_path)
response = client.put_file('/pass',f )

but it's not working

like image 546
Amro elaswar Avatar asked Mar 22 '15 00:03

Amro elaswar


People also ask

Can I upload an entire folder to Dropbox?

You can upload files and folders to your Dropbox account on dropbox.com and the Dropbox desktop app. Each file or folder uploaded on dropbox.com can be up to 50 GB. Each file or folder uploaded on the Dropbox desktop app can be up to 2 TB. You can also upload files with the Dropbox mobile app.

How do I upload files to Dropbox using Python?

To upload a file to Dropbox using Python we 'll use the dbx. files_upload() function. We'll use pathlib. Path() to create the right path to our local file we want to upload and will store it in local_file_path .

How can I upload an entire folder?

Step 1 – Open Google Drive and click the New button. Step 2 – Select File Upload and go to the location of the zip folder. Step 3 – Select the zip folder and click Open to begin the upload.


1 Answers

The Dropbox SDK doesn't automatically find all the local files for you, so you'll need to enumerate them yourself and upload each one at a time. os.walk is a convenient way to do that in Python.

Below is working code with some explanation in the comments. Usage is like this: python upload_dir.py abc123xyz /local/folder/to/upload /path/in/Dropbox:

import os
import sys

from dropbox.client import DropboxClient

# get an access token, local (from) directory, and Dropbox (to) directory
# from the command-line
access_token, local_directory, dropbox_destination = sys.argv[1:4]

client = DropboxClient(access_token)

# enumerate local files recursively
for root, dirs, files in os.walk(local_directory):

    for filename in files:

        # construct the full local path
        local_path = os.path.join(root, filename)

        # construct the full Dropbox path
        relative_path = os.path.relpath(local_path, local_directory)
        dropbox_path = os.path.join(dropbox_destination, relative_path)

        # upload the file
        with open(local_path, 'rb') as f:
            client.put_file(dropbox_path, f)

EDIT: Note that this code doesn't create empty directories. It will copy all the files to the right location in Dropbox, but if there are empty directories, those won't be created. If you want the empty directories, consider using client.file_create_folder (using each of the directories in dirs in the loop).

like image 198
user94559 Avatar answered Oct 19 '22 12:10

user94559