How to download files from sharepoint using its python client library?

Asnal Rizvi 5 Reputation points
2024-02-06T11:05:46.24+00:00

Description:
I am trying to download files from sharepoint using sharepoint's python client library. Even though i have correct permissions for the client i am still not able to download the files.

Code snippet:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
import os
from urllib.parse import quote ctx_auth = AuthenticationContext(site_url)
if ctx_auth.with_client_certificate(tenant=tenant_id, client_id=client_id,thumbprint= cert_thumbprint, private_key=private_key):
ctx = ClientContext(site_url, ctx_auth)
print(f"INFO: Connected to SharePoint site: {site_url}")
query = "filename.docx"
result = ctx.search.query(query).execute_query()
for row in result.value.PrimaryQueryResult.RelevantResults.Table.Rows:
file_url = row.Cells["OriginalPath"]
server_relative_url = "/" + file_url.replace(site_url,"")
file_path = os.path.join(output_folder, filename)
with open(file_path, "wb") as local_file:
ctx.web.get_file_by_server_relative_url(server_relative_url).download(local_file).execute_query()
print(f"INFO: File downloaded: {file_path}")

Error message: office365.runtime.client_request_exception.ClientRequestException: ('-2130575338, Microsoft.SharePoint.SPException', 'The file /teams/abc/Shared Documents/filename.docx does not exist.', "404 Client Error: Not Found for url: https://abc.sharepoint.com/_api/Web/getFileByServerRelativeUrl('%2Fteams%2Fabc%2FShared%20Documents%2Ffilename.docx')?$select=ServerRelativePath,Id")

Microsoft 365 and Office SharePoint For business Windows
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 40,471 Reputation points Microsoft External Staff
    2024-02-07T01:36:23.24+00:00

    Hi @Asnal Rizvi, You could try to set Shared Documents/filename.docx as file_path. Please refer to following code

    """
    Demonstrates how to download a file from SharePoint site
    """
    import os
    import tempfile
    from office365.sharepoint.client_context import ClientContext
    from tests import test_client_credentials, test_team_site_url
    ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
    file_url = "Shared Documents/big_buck_bunny.mp4"
    # file_url = "Shared Documents/!2022/Financial Sample.xlsx"
    download_path = os.path.join(tempfile.mkdtemp(), os.path.basename(file_url))
    with open(download_path, "wb") as local_file:
        file = (
            ctx.web.get_file_by_server_relative_url(file_url)
            .download(local_file)
            .execute_query()
        )
    print("[Ok] file has been downloaded into: {0}".format(download_path))
    
    
    

    ---If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.