Accessing Files From SharePoint Using Python

Mahaboob Basha
1 min readJun 10, 2021

This article will discuss on how to connect to SharePoint using Python and folders and files.

We will use library for connecting SharePoint is Office365-REST-Python-Client.

We need to install Office365-REST-Python-Client by using below command.

pip install Office365-REST-Python-Client

If you are not able to install with above command use below below mentioned command.

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

Please find below required functions to be imported for our requirement

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

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'])

Now we will constructing function for getting file details in SharePoint Folder

def folder_details(ctx, folder_in_sharepoint):  
folder = ctx.web.get_folder_by_server_relative_url(folder_in_sharepoint) fold_names = []
sub_folders = folder.files
ctx.load(sub_folders)
ctx.execute_query()
for s_folder in sub_folders: fold_names.append(s_folder.properties["Name"])
return fold_names

Now we will get folder details by calling above function

file_list = folder_details(ctx, folder_in_sharepoint) 
#Printing list of files from sharepoint folderprint(filelist_shrpt)

Now we will see how to read file from a SharePoint and save to local.

#Reading File from SharePoint Folder
sharepoint_file = '/teams/SustainabilityDataAccelerator/Shared%20Documents/General/Agro/2018_indirects_sustainable_sourcing_template.xlsx'
file_response = File.open_binary(ctx, sharepoint_file)
#Saving file to localwith
open("sharepointfile.csv", 'wb') as output_file: output_file.write(file_response.content)

Please find below full code

https://github.com/bashamsc/sharepoint_python

--

--