【问题标题】:Upload a file to a Sharepoint folder using Python使用 Python 将文件上传到 Sharepoint 文件夹
【发布时间】:2020-08-19 12:30:54
【问题描述】:

我有一个 Python 脚本,可以将文件保存到服务器共享文件夹以供用户访问。我们的组织最近将我们的服务器文件结构移动到了 Sharepoint... 包括所有文件夹。 (我已经阅读了多篇文章,这是一个坏主意,但现在没有改变它。)

我有将文件上传到 Sharepoint 库的根文件夹的新代码:

导入共享 s = sharepy.connect("site.sharepoint.com", "username", "password") r = s.post("https://site.sharepoint.com/_api/web/Lists/GetByTitle('Documents')/RootFolder/files\ /add(覆盖=true,url='test.csv')", \ “测试,富,酒吧”) 打印(r)

有没有办法将文件上传到子文件夹而不是根目录?如果有,怎么做?

【问题讨论】:

  • 一个可以作为临时解决方案但不直接上传到 SharePoint 的选项是将本地文件夹与 SharePoint 同步,并让您的 python 脚本将文件复制到本地文件夹。只要您登录以支持同步,您的文件就会上传到 SharePoint 并可供其他人使用。
  • 确实如此。我有几个可用的临时解决方案,但现在正在研究一个首选解决方案。谢谢!
  • 不客气。我对解决方案感兴趣。我的使用 2 因素身份验证很复杂,一旦输入,就会记住允许同步方法工作。稍后当它优先级上升时,我会重新讨论。祝你好运。
  • 谢天谢地,我没有处理 2 因素身份验证。我的解决方案如下。祝你好运!

标签: python sharepoint directory upload directory-structure


【解决方案1】:

是的,您可以通过 rest api 将文件上传到子文件夹。请参考以下端点:

下面是一些关于如何使用 python 上传文件的演示(但它们可能不会使用与您相同的库)。

/////// 更新 //////

【讨论】:

  • 我根据您上面的“创建文件并将其添加到文件夹”链接修改了我的代码。 import sharepy s = sharepy.connect("site.sharepoint.com", "username", "password") r = s.post("williamsburghealthfoundati.sharepoint.com/sites/ValerieTest/…\ GetFolderByServerRelativeUrl('/Folder1')/Files/\ add(overwrite= true,url='test.csv')", "testing,foo,bar") print(r) 我添加了一个特定的站点名称并合并了 GetFolderByServerRelativeUrl 调用。结果是响应 [400]。谢谢!
  • 400 是错误的请求。一般表示网址不正确。
  • 谢谢!我知道我的 URL 不正确,但找不到写入组合。我不得不在 URL 和 GetFolderByServerRelativeUrl 中重复站点/TeamSiteName 部分。
【解决方案2】:

如果它对任何人有帮助,这是我的最终代码。它成功地将文件发布到共享点站点团队站点库子文件夹。用您的信息替换斜体。

import sharepy 

s = sharepy.connect("*MySite*.sharepoint.com", "*username*", "*password*") 

r = s.post("https://*MySite*.sharepoint.com/sites/*TeamSiteName*/_api/web/GetFolderByServerRelativeUrl('/sites/*TeamSiteName*/Shared Documents/*FolderName*')/Files/" + "add(overwrite=true,url='test.csv')", "testing,foo,bar")

print r

【讨论】:

    【解决方案3】:

    前段时间我曾解决过同样的问题。下面是我的代码。

    import requests
    from shareplum import Office365
    
    username = "YourUsername"
    password = "YourPassword"
    site_name = "Sitename"
    doc_library = "SubfolderName"
    base_path = "https://domainName.sharepoint.com"
    
    file_name = "FileName"
    
    # Obtain auth cookie
    authcookie = Office365(base_path, username=username, password=password).GetCookies()
    session = requests.Session()
    session.cookies = authcookie
    session.headers.update({'user-agent': 'python_bite/v1'})
    session.headers.update({'accept': 'application/json;odata=verbose'})
    
    # dirty workaround.... I'm getting the X-RequestDigest from the first failed call
    session.headers.update({'X-RequestDigest': 'FormDigestValue'})
    response = session.post( url=base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='a.txt',overwrite=true)",
                             data="")
    session.headers.update({'X-RequestDigest': response.headers['X-RequestDigest']})
    
    dest =  base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='a.txt',overwrite=true)" #session.post( url=base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='a.txt',overwrite=true)",data="")
    print('Folder!')
    # perform the actual upload
    with open( file_name, 'rb') as file_input:
        try:
            print('uploading')
            response = session.post( 
                url=base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='" 
                + file_name + "',overwrite=true)",
                data=file_input)
        except Exception as err: 
            print("Some error occurred: " + str(err))
    print('Uploaded successfully!')
    

    【讨论】:

      【解决方案4】:

      经过这么多尝试,我终于用比我预期的更少的行编码完成了这项工作。

      我在某些 url 和文件夹路径方面遇到了一些问题,这就是为什么我将“r”放在获取原始路径的原因。

      来自 shareplum 导入站点 从 shareplum 导入 Office365 从 shareplum.site 导入版本

      普通认证

      authcookie = Office365(r'https://.sharepoint.com', username='@', password='***').GetCookies()

      在这里填写您网站上的信息

      site = Site(r'https://*******.sharepoint.com/sites/sitename/',version=Version.v365, authcookie=authcookie)

      在这里你只需填写文件夹的信息

      folder = site.Folder('共享文档/您的文件夹')

      来源:https://shareplum.readthedocs.io/en/latest/files.html#folders

      编码和错误是可选的

      使用 open(r'C:/Users/Alessandro.paiva/Desktop/file.xlsx', encoding = 'latin-1', errors = 'ignore') 作为文件: fileContent = file.read()

      文件名

      folder.upload_file(fileContent, r'file.xlsx')

      【讨论】:

        【解决方案5】:

        以下是我使用 Databricks 中的 python 将文件从 Azure Blob 存储上传到 Sharepoint 上的新子文件夹的代码。

        def upload_sharepoint(sp_filepath,blob_file_path):
          from office365.runtime.auth.authentication_context import AuthenticationContext
          from office365.sharepoint.client_context import ClientContext
          from office365.sharepoint.files.file import File
          import os
          
          url='https://<domain>.sharepoint.com/sites/<site1>/<subsite1>'
          username = 'user'
          pwd = 'password'
        
          ctx_auth = AuthenticationContext(url)
          ctx_auth.acquire_token_for_user(username, pwd)   
          ctx = ClientContext(url, ctx_auth)
        
          blobpath = '/dbfs' + blob_file_path
          filename=os.path.basename(blob_file_path)
          
          #read content of file
          with open(blobpath, 'rb') as content_file:
            file_content = content_file.read()
          
          target_url = sp_filepath  # sharepoint url to upload a file 
          target_folder=ctx.web.get_folder_by_server_relative_url(target_url)
          try:
            folder_exist=ctx.load(target_folder).execute_query().properties['Exists']
          except Exception as e:
            folder_exist=False
            print('Folder Not Found,Creating Folder')
            
          if !folder_exist:
            try:
              target_folder = ctx.web.folders.add(target_url).execute_query()    #Create the folder, can create folder upto 1 level only
            except Exception as e:
              print('Parent folder Not Found',e)
          target_folder.upload_file(filename, file_content).execute_query()    # upload the file
          print('Uploaded '+filename+' to '+target_url)
        

        以上代码可用于在已存在的文件夹中创建一级子文件夹。

        例如,在这里我们将在 Sharepoint 上存在的“支付文件”文件夹中创建一个文件夹名称“NewFolder”:

        sharepoint_fp='/sites/<site1>/<subsite1>/Document%20upload/Pay%20file/NewFolder' 
        blob_path='/mnt/PayFile/'  
        files=spark.createDataFrame(dbutils.fs.ls(blob_path))
        files=files.select('name').collect()
        for f in files:
          upload_sharepoint(sharepoint_fp,blob_path+f.name)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-11-10
          • 2018-12-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-11
          • 1970-01-01
          相关资源
          最近更新 更多