Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Download files from SharePoint site

I have a requirement of downloading and uploading the files to Sharepoint sites. This has to be done using python. My site will be as https://ourOrganizationName.sharepoint.com/Followed by Further links Initially I thought I could do this using Request, BeautifulSoup etc., But I am not at all able to go to "Inspect Element" on the body of the site.

I have tried libraries such as Sharepoint,HttpNtlmAuth,office365 etc., but I am not successful. It always returning 403.

I tried google as much I can but again not successful. Even Youtube hasn't helped me.

Could anyone help me how to do that? Suggestion on Libraries with documentation link is really appreciated.

Thanks

like image 839
DKS Avatar asked Dec 07 '18 14:12

DKS


People also ask

How do I download files from SharePoint online using Python?

Requirements: Install Office365 Python client. Initiate the authentication flow. Download the file from Microsoft SharePoint.

How do I download a file from SharePoint?

To start downloading files, find your file folder in SharePoint. Select the files you want to download by clicking the circles on the left side of the file name. Once you have the files selected, click the “Download” button in the command bar.


1 Answers

Have you tried Office365-REST-Python-Client library, it supports SharePoint Online authentication and allows to download/upload a file as demonstrated below:

Download a file

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File

ctx_auth = AuthenticationContext(url)
ctx_auth.acquire_token_for_user(username, password)   
ctx = ClientContext(url, ctx_auth)
response = File.open_binary(ctx, "/Shared Documents/User Guide.docx")
with open("./User Guide.docx", "wb") as local_file:
    local_file.write(response.content)

Upload a file

ctx_auth = AuthenticationContext(url)
ctx_auth.acquire_token_for_user(username, password)   
ctx = ClientContext(url, ctx_auth)

path = "./User Guide.docx" #local path
with open(path, 'rb') as content_file:
   file_content = content_file.read()
target_url = "/Shared Documents/{0}".format(os.path.basename(path))  # target url of a file 
File.save_binary(ctx, target_url, file_content) # upload a file

Usage

Install the latest version (from GitHub):

pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git

Refer file_operations.py for a more details

like image 97
Vadim Gremyachev Avatar answered Sep 20 '22 04:09

Vadim Gremyachev