Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file to sharepoint site using python script

Tags:

Is there a way to upload a file on sharepoint site using python script? I tried installing haufe.sharepoint, but it seems like it failed to fetch ntlm while it was installing, and I can't even use the connector module without having ntlm installed.

I've also tried just saving the excel file to the server location (so save it to directory like \server\sharepointsite\files instead of connecting via the URL) using openpyxl, but it looks like the file remains checked out after the file is saved..

I would appreciate any help. Thanks!!

like image 637
user3590460 Avatar asked May 16 '14 13:05

user3590460


People also ask

Can Python write to SharePoint list?

We recommend the third-party Python package "SharePlum," which provides an easy way to work with the SharePoint list and allows programmers to write clean Python code (Rollins, 2020).


2 Answers

I'll start by saying this example is adapted from the example for Office365-REST-Python-Client. It works with sharepoint online using the rest api.

https://github.com/vgrem/Office365-REST-Python-Client/blob/master/examples/sharepoint/files/upload_file.py

Example url you might want to upload to [baseurl][site][folder][file]. https://your_company.sharepoint.com/path/to/site/Shared Documents/file.txt

from office365.runtime.auth.authentication_context import AuthenticationContext from office365.sharepoint.client_context import ClientContext  baseurl = 'https://your_company.sharepoint.com' basesite = '/path/to/site' # every share point has a home. siteurl = baseurl + basesite   localpath = ./file.txt remotepath = Shared Documents/file.txt # existing folder path under sharepoint site.  ctx_auth = AuthenticationContext(url) ctx_auth.acquire_token_for_user(username, password) ctx = ClientContext(siteurl, ctx_auth) # make sure you auth to the siteurl.  with open(localpath, 'rb') as content_file:     file_content = content_file.read()  dir, name = os.path.split(remotepath) file = ctx.web.get_folder_by_server_relative_url(dir).upload_file(name, file_content).execute_query() 
like image 82
Josh Avatar answered Sep 20 '22 13:09

Josh


haufe.sharepoint only works for sharepoint lists, but you probably need access to document libraries.

You should use Python Requests with the help of Sharepoint's REST API.

If your sharepoint site doesn't support BasicAuth I recommend the requests_ntlm package.

It didn't work for me due to other reasons, but maybe it helps you out a bit.

like image 29
Calanas Avatar answered Sep 20 '22 13:09

Calanas