pythonsharepointsharepoint-api

Change file custom properties/columns in SharePoint with Python API


I'm trying update custom created column for files in a SharePoint using Python API.


Solution

  • Follwing function will update a property/column.

    def update_sp_file_property(
        ctx: ClientContext, filepath: str, properties: dict
    ) -> None:
        """
        Update sharepoint files customn properties (columns)
    
        Args:
            ctx: ClientContext
            filepath: serverRelativePath to file
            properties: dict of properties to update
        Returns:
            None
        """
    
        # Create query for property update
        for k, v in properties.items():
            updates = (
                ctx.web.get_file_by_server_relative_path(filepath)
                .listItemAllFields.set_property(name=k, value=v, persist_changes=True)
                .update()
                .execute_query()
            )
            print(f'Updated {os.path.basename(filepath)} property: "{k}" : "{v}"')
    
        # Send query
        updates.execute_query()
    
    

    Run as follow:

    # Define parameters
    client_id = cfg["SHAREPOINT"]["CLIENT_ID"]
    client_secret = cfg["SHAREPOINT"]["CLIENT_SECRET"]
    base_url = cfg["SHAREPOINT"]["BASE_URL"]
    
    Create sharepoint context for auth
    ctx = sp.get_client_context(
            client_id=client_id, client_secret=client_secret, base_url=base_url
        )
    filepath = "/sites/<sharepoint_site_name>/Shared Documents/General/path_to_file"
    properties = {
        "property1": "value1",
        "property2": "value2",
      }
    
    # Run fucntion
    update_sp_file_property(ctx=ctx, filepath=filepath, properties=properties)