Upload multiple *.docx files from folder into the sharepoint

Hello All…I have multiple *.docx files in server folder…I want to upload those files into sharepoint using python. Please help me on how to get it done…thanks a lot.

Do you know how to upload one file? Do you know how to get the names of the files? Do you know how to repeat the code with each file name? Where are you stuck?

To upload multiple *.docx files from a server folder to SharePoint using Python, you can use the ‘sharepy’ library to authenticate and interact with the SharePoint REST API. You’ll also need to use the ‘requests’ library to handle the file upload process.

First, make sure you have the required libraries installed. You can install them using pip:

bashCopy code

pip install sharepy
pip install requests

Now, you can follow the steps below to upload the files:

  1. Authenticate and connect to SharePoint:

pythonCopy code

import sharepy

site_url = "https://your_domain.sharepoint.com/sites/your_site"
username = "your_username@your_domain.com"
password = "your_password"

# Authenticate and connect to SharePoint
sp = sharepy.connect(site_url, username, password)
  1. Define a function to upload the files:

pythonCopy code

import os
import requests

def upload_file_to_sharepoint(sp, local_path, sharepoint_folder_url):
    file_name = os.path.basename(local_path)

    # Read the file data
    with open(local_path, "rb") as file:
        file_data = file.read()

    # Upload the file to SharePoint
    headers = {
        "accept": "application/json;odata=verbose",
        "content-type": "application/octet-stream",
        "odata-version": "",
        "X-RequestDigest": sp.form_digest,
        "binaryStringRequestBody": "true"
    }

    url = f"{sp.site_url}/_api/web/GetFolderByServerRelativeUrl('{sharepoint_folder_url}')/Files/add(url='{file_name}', overwrite=true)"
    response = sp.post(url, data=file_data, headers=headers)

    if response.status_code == 200:
        print(f"File '{file_name}' uploaded successfully.")
    else:
        print(f"Failed to upload file '{file_name}'.")
  1. Use the function to upload all the *.docx files from the server folder:

pythonCopy code

import glob

server_folder = "/path/to/your/server/folder"
sharepoint_folder_url = "/sites/your_site/Documents"

# Find all the *.docx files in the server folder
docx_files = glob.glob(f"{server_folder}/*.docx")

# Upload each file to SharePoint
for file in docx_files:
    upload_file_to_sharepoint(sp, file, sharepoint_folder_url)

Replace the placeholders with your actual SharePoint site URL, username, password, server folder path, and SharePoint folder URL. The script will then upload all the *.docx files from your server folder to the specified SharePoint folder.

1 Like

Thank you so much!