pythonpython-3.xsharepointoffice365api

File Download from Sharepoint using Python


I am trying to download an excel file from Sharepoint with the office365 module. Here's my code.

   from office365.runtime.auth.authentication_context import AuthenticationContext
   from office365.sharepoint.client_context import ClientContext
   from office365.sharepoint.file import File
   app_settings = {
     'url': 'https://xxxxx/sites/DownloadFiles',
     'client_id': 'xxxxxx',
     'client_secret': 'xxxxxx',
   }
   if name == 'main':
      ctx_auth = AuthenticationContext(url=app_settings['url'])
      ctx_auth.acquire_token_for_app(client_id=app_settings['client_id'], 
      client_secret=app_settings['client_secret'])
      ctx = ClientContext(app_settings['url'], ctx_auth)

      path = "F:\myexcel.xlsx"
      response = File.open_binary(ctx, "/Shared%20Documents/myexcel.xlsx")
      response.raise_for_status()
      with open(path, "wb") as local_file:
           local_file.write(response.content)

When I run that code, I get the following error:

400 Client Error: Bad Request for url: https://xxx/DownloadFiles/_api/web/getfilebyserverrelativeurl('/Shared%20Documents/myexcel.xlsx')/%5C$value

Solution

  • I am able to reproduce the same issue on my SPO. enter image description here

    Please modify the code as below to fix it:

    response = File.open_binary(ctx, "/sites/{abc}/Shared%20Documents/source.txt")
    

    Such as i want to download file from a site collection like "https://xxxx.sharepoint.com/sites/abc", the serverrelativeurl is "/sites/abc"

    You can get the serverrelativeurl via '_spPageContextInfo' object:

    enter image description here

    And there is another SharePoint library 'shareplum' that provided some easy ways to operate files, you may have a try.

    Best Regards, Baker Kong