如何使用python将完整文件夹上传到Dropbox

问题描述 投票:4回答:1

我试图立即将整个文件夹上传到Dropbox,但我似乎无法完成它是否可能? 即使我在尝试上传单个文件时,我必须在Dropbox路径中精确定位文件扩展名,还有其他方法吗? 我正在使用的代码

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

但它不起作用

python python-2.7 dropbox-api
1个回答
6
投票

Dropbox SDK不会自动为您找到所有本地文件,因此您需要自己枚举它们并一次上传每个文件。 os.walk是在Python中执行此操作的便捷方式。

下面是工作代码,在评论中有一些解释。 用法是这样的: 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)

编辑 :请注意,此代码不会创建空目录。 它会将所有文件复制到Dropbox中的正确位置,但如果有空目录,则不会创建这些文件。 如果您想要空目录,请考虑使用client.file_create_folder (使用循环中dirs中的每个dirs )。

© www.soinside.com 2019 - 2024. All rights reserved.