Not able to get folders which are inside folder with name containing special Charaters using sharepoint API

Vinit Jain 1 Reputation point
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

url = ""
site_url = url + "/xxxx/xxxx/xxxx"

def auth_api(user, pas):                                                        
    ctx_auth = AuthenticationContext(url)                                       
    ctx_auth.acquire_token_for_user(user, pas)                                  
    ctx = ClientContext(siteurl, ctx_auth) # make sure you auth to the siteurl. 
    return ctx                                                                  

def folder_check(user, pas, folder_path, folder_to_check):
       ctx = auth_api(user, pas)                                                        
       libraryRoot = ctx.web.get_folder_by_server_relative_url(folder_path)           
       folders = libraryRoot.folders                                                  
       ctx.execute_query() #Breaks here                                                         
       for myfolder in folders:                                                       
           if folder_to_check in["ServerRelativeUrl"]:                                                               
               return {'status': True,'message':'Folder Found'}                       
       return {'status': False,'message':'Folder Not Found'}                          
   except Exception as e:                                                             
       return {'status': False,'message':str(e)}                                      

folder_check('xxxxx', 'xxxx', "user # test", "test")

folder abc#123 contain folder test
but it is not printing test

A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,214 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Kelly Taber 1 Reputation point


    This is the problem with spaces and characters in SharePoint. You will have to replace them with the Ascii Hex codes ( In this case you are going to replace the # with %23.
    Hope this helps.

  2. MichaelHan-MSFT 18,001 Reputation points

    Hi @Vinit Jain ,

    In C#, we use ResourcePath API to deal with special charaters, then use method Web.GetFolderByServerRelativePath(ResourcePath) instead of Web.GetFolderByServerRelativeUrl(String) to get the folder.

    And this method is not available in python :

    So, i think you may need to use the method get_folder_by_id() to get the folder.

    If an Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.