Mahaboob Basha
1 min readOct 27, 2021

--

Uploading Files To SharePoint Using Python

This article will discuss on how to upload files to SharePoint using Python.

How to install required libraries and usage of libraries you can go through in below article of mine.

Now Constructing SharePoint URL ,Folder Details and Credentials

sharepoint_base_url = ‘https://mycompany.sharepoint.com/teams/sharepointname/'
sharepoint_user = ‘user’
sharepoint_password = ‘pwd’
folder_in_sharepoint = ‘/teams/sharepointname/Shared%20Documents/YourFolderName/’

Now we will authenticate and connect to SharePoint

auth = AuthenticationContext(sharepoint_base_url) auth.acquire_token_for_user(sharepoint_user, sharepoint_password)ctx = ClientContext(sharepoint_base_url, auth)web = ctx.webctx.load(web)ctx.execute_query()print(‘Connected to SharePoint: ‘,web.properties[‘Title’])

Reading the file to be uploaded

fileName = ‘C:\\path\\file.xlsx’

Reading file content

with open(fileName, ‘rb’) as content_file:
file_content = content_file.read()

Reading file name

name = os.path.basename(fileName)

Initializing root directory of SharePoint

root_dir = “Documents”

Getting the target list

target_list = ctx.web.lists.get_by_title(root_dir)
info = FileCreationInformation()
libraryRoot = ctx.web.get_folder_by_server_relative_url(folder_url_shrpt)

Uploading file to SharePoint

target_file = libraryRoot.upload_file(name, file_content).execute_query()
print(“File has been uploaded to url: {0}”.format(target_file.serverRelativeUrl))

Please find below full code

https://github.com/bashamsc/sharepoint_python/blob/main/sharepoint_upload_file_python.py

--

--