加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Dropbox API v2 – 上传文件

发布时间:2020-12-20 11:47:09 所属栏目:Python 来源:网络整理
导读:我正在尝试遍历 python中的文件夹结构,并将找到的每个文件上传到指定的文件夹.问题是它上传的文件名正确,但没有内容,文件大小只有10个字节. import dropbox,sys,ostry: dbx = dropbox.Dropbox('some_access_token') user = dbx.users_get_current_account()e
我正在尝试遍历 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,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,files"
for dir,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 %sn%s" % (file,err))

print("Finished upload.")

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读