简体   繁体   English

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

[英]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? 我试图立即将整个文件夹上传到Dropbox,但我似乎无法完成它是否可能? 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? 即使我在尝试上传单个文件时,我必须在Dropbox路径中精确定位文件扩展名,还有其他方法吗? 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 但它不起作用

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. Dropbox SDK不会自动为您找到所有本地文件,因此您需要自己枚举它们并一次上传每个文件。 os.walk is a convenient way to do that in Python. os.walk是在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 : 用法是这样的: 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. 它会将所有文件复制到Dropbox中的正确位置,但如果有空目录,则不会创建这些文件。 If you want the empty directories, consider using client.file_create_folder (using each of the directories in dirs in the loop). 如果您想要空目录,请考虑使用client.file_create_folder (使用循环中dirs中的每个dirs )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM