The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Sync files to Dropbox with Python

Synchronizing files to Dropbox using Python can be done efficiently with the Dropbox API. This tutorial-style article will walk through setting up a Python script to upload, update, and sync files between a local directory and a Dropbox folder.


Prerequisites

Before getting started, ensure the following:

  • Python 3.x is installed.

  • A Dropbox account is available.

  • Dropbox API access token is created.

  • The dropbox Python SDK is installed.

You can install the Dropbox SDK using pip:

bash
pip install dropbox

Create an app in the Dropbox App Console and generate an access token.


Set Up the Dropbox Client in Python

To begin, initialize the Dropbox client using the access token.

python
import dropbox ACCESS_TOKEN = 'your_access_token_here' dbx = dropbox.Dropbox(ACCESS_TOKEN)

To verify the connection:

python
dbx.users_get_current_account()

If no exception is raised, you’re connected successfully.


Upload a File to Dropbox

The core functionality starts with uploading files. The following script uploads a single file to a target Dropbox path.

python
def upload_file(local_path, dropbox_path): with open(local_path, "rb") as f: dbx.files_upload(f.read(), dropbox_path, mode=dropbox.files.WriteMode("overwrite"))

Usage example:

python
upload_file("local_folder/sample.txt", "/remote_folder/sample.txt")

List Files in a Dropbox Folder

To sync files intelligently, you’ll often need to compare file lists. Here’s how to list files in a Dropbox directory:

python
def list_files_in_dropbox_folder(folder_path): files = [] result = dbx.files_list_folder(folder_path) files.extend([entry.name for entry in result.entries]) while result.has_more: result = dbx.files_list_folder_continue(result.cursor) files.extend([entry.name for entry in result.entries]) return files

Sync Local Directory to Dropbox

The following function walks through a local folder and syncs each file to Dropbox.

python
import os def sync_folder(local_folder, dropbox_folder): for root, _, files in os.walk(local_folder): for filename in files: local_path = os.path.join(root, filename) relative_path = os.path.relpath(local_path, local_folder) dropbox_path = f"{dropbox_folder}/{relative_path}".replace("\", "/") print(f"Uploading {local_path} to {dropbox_path}...") upload_file(local_path, dropbox_path)

Example usage:

python
sync_folder("my_local_folder", "/my_dropbox_folder")

This will recursively upload all files while maintaining the directory structure.


Handling Modified Files (Advanced Sync)

A basic improvement includes only uploading files that have been changed. For that, compare metadata like file size, hash, or modification time. Here’s a hash comparison approach:

python
import hashlib def get_local_file_hash(file_path): hasher = hashlib.md5() with open(file_path, "rb") as f: while chunk := f.read(4096): hasher.update(chunk) return hasher.hexdigest() def get_dropbox_file_hash(dropbox_path): try: metadata = dbx.files_get_metadata(dropbox_path) return metadata.content_hash except dropbox.exceptions.ApiError: return None

Now integrate this into the sync function:

python
def sync_folder_with_hash_check(local_folder, dropbox_folder): for root, _, files in os.walk(local_folder): for filename in files: local_path = os.path.join(root, filename) relative_path = os.path.relpath(local_path, local_folder) dropbox_path = f"{dropbox_folder}/{relative_path}".replace("\", "/") local_hash = get_local_file_hash(local_path) dropbox_hash = get_dropbox_file_hash(dropbox_path) if local_hash != dropbox_hash: print(f"Syncing: {local_path}{dropbox_path}") upload_file(local_path, dropbox_path) else: print(f"Unchanged: {local_path}")

This ensures only modified files are uploaded.


Delete Files in Dropbox Not Found Locally

To keep Dropbox in sync with the local directory, you may also want to remove files from Dropbox that no longer exist locally:

python
def delete_removed_files(local_folder, dropbox_folder): local_files = set() for root, _, files in os.walk(local_folder): for filename in files: relative_path = os.path.relpath(os.path.join(root, filename), local_folder) local_files.add(relative_path.replace("\", "/")) dropbox_files = list_files_in_dropbox_folder(dropbox_folder) dropbox_files_set = set(dropbox_files) files_to_delete = dropbox_files_set - local_files for file in files_to_delete: dropbox_path = f"{dropbox_folder}/{file}" try: dbx.files_delete_v2(dropbox_path) print(f"Deleted from Dropbox: {dropbox_path}") except Exception as e: print(f"Error deleting {dropbox_path}: {e}")

Combine this with the sync operation for full bidirectional sync behavior.


Error Handling and Logging

Robust scripts need logging and exception handling. Add basic try-except blocks:

python
def safe_upload_file(local_path, dropbox_path): try: upload_file(local_path, dropbox_path) print(f"Uploaded: {local_path}") except Exception as e: print(f"Failed to upload {local_path}: {e}")

Or use the logging module for a more scalable solution:

python
import logging logging.basicConfig(level=logging.INFO, filename="sync.log") def log_upload_file(local_path, dropbox_path): try: upload_file(local_path, dropbox_path) logging.info(f"Uploaded: {local_path} to {dropbox_path}") except Exception as e: logging.error(f"Error uploading {local_path}: {e}")

Security Considerations

Never hardcode access tokens in production scripts. Instead:

  • Use environment variables.

  • Use secure secret management tools like AWS Secrets Manager or HashiCorp Vault.

  • Regularly rotate access tokens.

Example using environment variables:

python
import os ACCESS_TOKEN = os.getenv("DROPBOX_ACCESS_TOKEN")

Run the script with:

bash
DROPBOX_ACCESS_TOKEN=your_token python sync_script.py

Automating with Schedulers

Use OS-level task schedulers to automate syncing:

  • Windows: Task Scheduler

  • macOS/Linux: cron

Example cron job (runs every hour):

bash
0 * * * * /usr/bin/python3 /home/user/dropbox_sync.py

Conclusion

Syncing files to Dropbox using Python offers a flexible solution for cloud backups, distributed team collaboration, or automated content delivery. With the Dropbox API and proper hashing, it’s easy to develop a custom sync tool tailored to specific needs. This script can serve as the foundation for full-featured Dropbox sync utilities with logging, error management, and versioning.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About