I want to get the list of all files in my personal oneDrive/sharepoint within my company via python. However, I only get an empty list as a return without any errors.
My code looks as follows (taken from Sharepoint_files_python:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.files.file import File
import io
user = 'user'
pw = 'pw'
url = 'https://company-my.sharepoint.com'
rel_url = '/personal/name_company/Documents/further/path/to/folder/'
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(user, pw):
ctx = ClientContext(url, ctx_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print('Authenticated into sharepoint as: ',web.properties['Title'])
else:
print(ctx_auth.get_last_error())
folder = ctx.web.get_folder_by_server_relative_url(rel_url)
fold_names = []
sub_folders = folder.files #Replace files with folders for getting list of folders
ctx.load(sub_folders)
ctx.execute_query()
for s_folder in sub_folders:
fold_names.append(s_folder.properties["Name"])
print(fold_names)
This gives an empty list as an output: []
And everything else I try to access within the ctx.web is empty as well, e.g.:
root_folder = ctx.web.default_document_library().root_folder
ctx.load(root_folder,['Files'])
ctx.execute_query()
for f in root_folder.files:
print(f.name)
[]
My expected outcome would be: ['file.xlsx','file_35.xlsx',....]
However, I can directly access individual files (but these are updated and change and thus not practical for hardcoding) in that folder via:
url = 'https://company-my.sharepoint.com/personal/name_company/Documents/further/path/to/folder/file.xlsx'
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(user, pw):
ctx = ClientContext(url, ctx_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Authentication successful")
else:
print(ctx_auth.get_last_error())
resp = File.open_binary(ctx,url)
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(resp.content)
bytes_file_obj.seek(0) #set file object to start
df = pd.read_excel(bytes_file_obj,engine='openpyxl',header=0)
print(df)
I get the expected outcome of the file being read and being available in python.
Does anyone know why there is no error when executing the on full sharepoint working code and how I can retrieve the list of files in my folder?