Skip to content

Instantly share code, notes, and snippets.

@hyunjong-lee
Created August 20, 2021 08:01
Show Gist options
  • Save hyunjong-lee/e0f97aa0e4c353c65c31b596765ee641 to your computer and use it in GitHub Desktop.
Save hyunjong-lee/e0f97aa0e4c353c65c31b596765ee641 to your computer and use it in GitHub Desktop.
List directories and files using Office365-REST-Python-Client library
import os
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file_system_object_type import FileSystemObjectType
tenant = '{YOUR tenant ID in HERE}'
tenant_name = '{YOUR TENENT NAME in HERE}'
site_name = '{YOUR SITE NAME in HERE}'
site_url = f"https://{tenant_name}.sharepoint.com/sites/{site_name}"
cert_settings = {
'client_id': '{YOUR CLIENT ID in HERE - Azure App}',
'thumbprint': '{YOUR CERTIFICATE thumbprint in HERE}',
'certificate_path': '{YOUR PRIVATE CERTIFICATE file path in HERE}',
}
ctx = ClientContext.from_url(site_url).with_client_certificate(tenant,
cert_settings.get('client_id'),
cert_settings.get('thumbprint'),
cert_settings.get('certificate_path'))
doc_lib = ctx.web.lists.get_by_title("Documents")
items = doc_lib.items.select(["FileSystemObjectType"]).expand(["File", "Folder"]).get().execute_query()
for item in items: # type: ListItem
if item.file_system_object_type == FileSystemObjectType.Folder:
print("Folder url: {0}".format(item.folder.serverRelativeUrl))
else:
print("File url: {0}".format(item.file.serverRelativeUrl))
@JavierMedel
Copy link

I'm getting the next error. Do you know if something change in the library?

Cell In[64], line 2
1 doc_lib = ctx.web.lists.get_by_title("Documents")
----> 2 items = doc_lib.items.select(["FileSystemObjectType"]).expand(["File", "Folder"]).get().execute_query()

AttributeError: 'ListItemCollection' object has no attribute 'get'

@hyunjong-lee
Copy link
Author

hyunjong-lee commented Mar 4, 2023

@JavierMedel Can you give me the result of the following code?

expand_res = doc_lib.items.select(["FileSystemObjectType"]).expand(["File", "Folder"])
dir(expand_res)

The library contains exactly same code as mine as a example.

@anjanesh
Copy link

From this - https://github.com/vgrem/Office365-REST-Python-Client/blob/master/examples/sharepoint/folders/list_folders.py

just add

for file in folder.files:
     print(file.name)
def enum_folder(parent_folder, action):
    """
    :type parent_folder: Folder
    :type action: (Folder)-> None
    """
    parent_folder.expand(["Folders", "Files"]).get().execute_query()
    action(parent_folder)
    for folder in parent_folder.folders:
        enum_folder(folder, action)
        
        for file in folder.files:
            print(file.name)

@hyunjong-lee
Copy link
Author

@anjanesh Great, Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment