post image

Python SharePoint Automation 10 Practical Examples


Microsoft SharePoint is a powerful collaboration and document‑management platform, but many daily tasks, like copying files, updating lists, or cleaning up folders, are slow and repetitive if done manually. Python can automate most of these jobs using SharePoint’s REST API or Microsoft Graph API, often via libraries like Office365-REST-Python-Client or the msgraph ecosystem. Once configured, a small script can handle hundreds of files, lists, or users in seconds.

This is especially useful for:

  • Syncing files between SharePoint and local or cloud storage.
  • Automating approvals, metadata updates, or cleanup workflows.
  • Extracting and reporting on SharePoint list data.
  • Creating and managing folders, libraries, or sites at scale.

Below are 10 practical examples you can adapt for your own SharePoint environment.


1. Setup: Connect to SharePoint (Office365‑REST‑Python‑Client)

Before you can automate anything, you need secure access. Here we use Office365‑REST‑Python‑Client.

Install:

pip install Office365-REST-Python-Client

Sample script to connect:

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

site_url = "https://yourcompany.sharepoint.com/sites/YourSite"
username = "admin@yourcompany.com"
password = "yourpassword"

ctx_auth = AuthenticationContext(site_url)
if ctx_auth.acquire_token_for_user(username, password):
ctx = ClientContext(site_url, ctx_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Connected to SharePoint site:", web.properties['Title'])
else:
print("Authentication failed:", ctx_auth.get_last_error())

This pattern is the base for all the examples below.


2. List all files in a SharePoint library

Read the contents of a document library (e.g., Shared Documents).

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

site_url = "https://yourcompany.sharepoint.com/sites/YourSite"
username = "..."
password = "..."

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

relative_url = "/sites/YourSite/Shared Documents"

folder = ctx.web.get_folder_by_server_relative_url(relative_url)
files = folder.files
ctx.load(files)
ctx.execute_query()

for file in files:
print("File:", file.properties["Name"], "| Size:", file.properties["Length"])

Use case: audit or log all files in a library before cleanup.


3. Upload a file to SharePoint

Automate uploads of reports, invoices, or templates.

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

site_url = "https://yourcompany.sharepoint.com/sites/YourSite"
username = "..."
password = "..."

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

relative_url = "/sites/YourSite/Shared Documents"

folder = ctx.web.get_folder_by_server_relative_url(relative_url)
local_path = "daily_report.pdf"

with open(local_path, "rb") as file_content:
file = folder.upload_file("daily_report_" + datetime.now().strftime("%Y%m%d") + ".pdf", file_content)
ctx.execute_query()

print("File uploaded:", file.properties["ServerRelativeUrl"])

Use case: push daily/weekly reports from an automation pipeline into SharePoint.


4. Download files from SharePoint to local disk

Pull files from SharePoint for local processing or backup.

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

site_url = "..."
username = "..."
password = "..."

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

relative_url = "/sites/YourSite/Shared Documents/example.xlsx"

file = ctx.web.get_file_by_server_relative_url(relative_url)
data = file.download(ctx).execute_query()

download_path = "downloads/example.xlsx"
os.makedirs(os.path.dirname(download_path), exist_ok=True)

with open(download_path, "wb") as local_file:
local_file.write(data.content)

print("File downloaded:", download_path)

Use case: sync the latest version of a file into your Python‑based ETL or reporting process.


5. Create a folder in a document library

If you need to create project folders, monthly folders, or client‑wise folders automatically.

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

site_url = "https://yourcompany.sharepoint.com/sites/YourSite"
username = "..."
password = "..."

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

relative_parent = "/sites/YourSite/Shared Documents"

parent_folder = ctx.web.get_folder_by_server_relative_url(relative_parent)
new_folder = parent_folder.folders.add("Project_April_2026")
ctx.execute_query()

print("Created folder:", new_folder.serverRelativeUrl)

Use case: at the start of each month or project, auto‑create a structured folder tree.


6. Read and print items from a SharePoint list

Use lists for approvals, tickets, or task tracking. Python can read them into Pandas or JSON.

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

site_url = "..."
username = "..."
password = "..."

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

list_title = "Tasks"

tasks_list = ctx.web.lists.get_by_title(list_title)
items = tasks_list.items
ctx.load(items)
ctx.execute_query()

for item in items:
print("ID:", item.properties["Id"], "Title:", item.properties["Title"])

Use case: generate daily dashboards or export to Excel/CSV from a task list.


7. Add a new item to a SharePoint list

Turn a Python script into a “ticket creation” or “approval request” engine.

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

site_url = "..."
username = "..."
password = "..."

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

list_title = "Requests"

requests_list = ctx.web.lists.get_by_title(list_title)

item_data = {
"Title": "New Software Request",
"RequestedBy": "Jitendra",
"Status": "Pending",
"Priority": "High"
}

new_item = requests_list.add_item(item_data)
ctx.execute_query()

print("Created list item ID:", new_item.properties["Id"])

Use case: connect a web form or workflow (e.g., n8n, Power Automate) to add SharePoint items via Python.


8. Update metadata on a SharePoint file

Update properties like Status, Owner, or ApprovedBy on a file.

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

site_url = "..."
username = "..."
password = "..."

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

file_url = "/sites/YourSite/Shared Documents/contract_v1.pdf"

file = ctx.web.get_file_by_server_relative_url(file_url)
ctx.load(file)
ctx.execute_query()

item = file.list_item_all_fields
item.set_property("Status", "Approved")
item.set_property("ApprovedBy", "Jitendra")
item.update()
ctx.execute_query()

print("File metadata updated:", file_url)

Use case: close a manual approval step and update the file’s status programmatically.


9. Move or copy files within SharePoint

Bulk‑move or copy from a “Draft” folder to “Approved” or from one library to another.

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

site_url = "https://yourcompany.sharepoint.com/sites/YourSite"
username = "..."
password = "..."

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

source_url = "/sites/YourSite/Shared Documents/Drafts/offer.pdf"
dest_folder = "/sites/YourSite/Shared Documents/Approved"

file = ctx.web.get_file_by_server_relative_url(source_url)
file.copyto(dest_folder + "/offer.pdf", True)
ctx.execute_query()

print("File copied to:", dest_folder)

Use case: clean up “Drafts” folders after approval and move approved files to a controlled area.


10. Bulk‑delete files older than N days

Automate cleanup of old files or temporary uploads.

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

site_url = "..."
username = "..."
password = "..."

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

relative_url = "/sites/YourSite/Shared Documents/Temp"

folder = ctx.web.get_folder_by_server_relative_url(relative_url)
files = folder.files
ctx.load(files)
ctx.execute_query()

threshold = datetime.now() - timedelta(days=30)

for file in files:
created = file.properties["TimeCreated"]
file_dt = datetime.strptime(created, "%Y-%m-%dT%H:%M:%SZ")
if file_dt < threshold:
file.delete_object()
print("Deleted:", file.properties["Name"])

ctx.execute_query()

Use case: enforce a “retain 30 days” policy in temp or upload folders.


How to Use Python with SharePoint

You can integrate these scripts into your daily workflow in several ways:

  1. Run manually for one‑off cleanups or migrations.
  2. Schedule scripts (cron, Windows Task Scheduler, Azure Functions, or n8n) to auto‑sync files, update lists, or purge old data.
  3. Chain with other tools:
    • Read Excel from SharePoint → process with pandas → push back as updated .xlsx.
    • Read a SharePoint list → generate Word reports → upload the reports back to SharePoint.

Best libraries and patterns

  • Office365‑REST‑Python‑Client (SharePoint): Great for direct SharePoint‑centric work (files, lists, folders).
  • msgraph / python‑msgraph: Better if you want to mix SharePoint with other Microsoft 365 services (OneDrive, Teams, etc.).
  • pandas + requests + msal: Good for advanced ETL where you call the Microsoft Graph REST API directly.

For most office‑automation use cases, Office365‑REST‑Python‑Client for SharePoint is the easiest starting point.


Final thoughts

Python extends SharePoint automation, reporting, and bulk‑operations power. If you are already using Python to automate Excel and Word, adding SharePoint automation lets you turn scattered, manual tasks, across files, lists, and sites, into a single, repeatable pipeline that handles your daily SharePoint work in minutes instead of hours.

Jitendra Chaudhary
Follow me

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top