[Python] How to interact with sharepoint via python?

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to access a spreadsheet that is stored on a sharepoint instance. The weird URL of that spreadsheet is like

    https://my.sharepoint.com/:x:/r/sites/myfolder/_layouts/15/doc2.aspx?sourcedoc=%7B0771C2D0-ED13-416F-B56E-696A9BC6F27C%7D&file=My%20JIRA%20file.xlsx&fromShare=true&action=default&mobileredirect=true


    but I see that file exists in a folder

    https://my.sharepoint.com/sites/myfolder


    with the name

    My JIRA file.xlsx


    The code I am using is the following:

    from office365.runtime.auth.authentication_context import AuthenticationContext
    from office365.sharepoint.client_context import ClientContext

    ctx_auth = AuthenticationContext(sharepoint_url)
    if ctx_auth.acquire_token_for_user(username, password):
    ctx = ClientContext(sharepoint_url, ctx_auth)
    web = ctx.web
    ctx.load(web)
    ctx.execute_query()

    # Download the Excel file
    response = File.open_binary(ctx, relative_file_url)


    with the proper username and password and with sharepoint_url="https://my.sharepoint.com/sites/myfolder" and relative_file_url="My JIRA file.xlsx"

    but get an error:

    Traceback (most recent call last):
    File "/home/alex/Work/edit_sharepoint_xls.py", line 47, in <module>
    response = File.open_binary(ctx, relative_file_url)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/home/alex/.pyenv/versions/3.11.10/lib/python3.11/site-packages/office365/sharepoint/files/file.py", line 649, in open_binary
    response = context.pending_request().execute_request_direct(request)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/home/alex/.pyenv/versions/3.11.10/lib/python3.11/site-packages/office365/runtime/client_request.py", line 101, in execute_request_direct
    response.raise_for_status()
    File "/home/alex/.pyenv/versions/3.11.10/lib/python3.11/site-packages/requests/models.py", line 1024, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
    requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://my.sharepoint.com/sites/myfolder/_api/web/getFileByServerRelativePath%28DecodedUrl%3D%27My%20JIRA%20file.xlsx%27%29/%5C%24value


    So what am I doing wrong here?

    Continue reading...

Compartilhe esta Página