编程语言
首页 > 编程语言> > python – Dropbox API v2 – 上传文件

python – Dropbox API v2 – 上传文件

作者:互联网

我正在尝试遍历python中的文件夹结构,并将找到的每个文件上传到指定的文件夹.问题是它上传的文件名正确,但没有内容,文件大小只有10个字节.

import dropbox, sys, os
try:
  dbx = dropbox.Dropbox('some_access_token')
  user = dbx.users_get_current_account()
except:
  print ("Negative, Ghostrider")
  sys.exit()

rootdir = os.getcwd()

print ("Attempting to upload...")
for subdir, dirs, files in os.walk(rootdir):
      for file in files:
        try:  
          dbx.files_upload("afolder",'/bfolder/' + file, mute=True)
          print("Uploaded " + file)
        except:
          print("Failed to upload " + file)
print("Finished upload.")

解决方法:

您对dbx.files_upload(“afolder”,’/ bfolder /’文件,mute = True)的调用说:“发送文本afolder并将其写为名为’/ bfolder /’file的文件”.

doc开始:

files_upload(f, path, mode=WriteMode(‘add’, None), autorename=False, client_modified=None, mute=False)
Create a new file with the contents provided in the request.

Parameters:

  • f – A string or file-like obj of data.
  • path (str) – Path in the user’s Dropbox to save the file.
    ….

意味着f必须是文件的内容(而不是文件名字符串).

这是一个工作示例:

import dropbox, sys, os

dbx = dropbox.Dropbox('token')
rootdir = '/tmp/test' 

print ("Attempting to upload...")
# walk return first the current folder that it walk, then tuples of dirs and files not "subdir, dirs, files"
for dir, dirs, files in os.walk(rootdir):
    for file in files:
        try:
            file_path = os.path.join(dir, file)
            dest_path = os.path.join('/test', file)
            print 'Uploading %s to %s' % (file_path, dest_path)
            with open(file_path) as f:
                dbx.files_upload(f, dest_path, mute=True)
        except Exception as err:
            print("Failed to upload %s\n%s" % (file, err))

print("Finished upload.")

编辑:对于Python3,应使用以下内容:

dbx.files_upload(f.read(),dest_path,mute = True)

标签:dropbox-api,python
来源: https://codeday.me/bug/20190727/1556898.html