Download all pdf files in a Sharepoint folder and some of its sub-folders using Python?

Viewed 107

I have a Sharepoint folder, where everyday, a few sub folders will be created and each of sub-folders will have a pdf file. Using python, I would like to download all the pdf files from these sub folders (except sub folders named 'Archive' and 'Completed') to a local folder location, do some analysis and upload each file back to the same sub folders in the Sharepoint location.

Here is the code for downloading I have tried till now. But wont specifically look for pdf files . It also wont recursively looking for sub folders inside /Dis Out. The sub folders will have different names every time except 'Archive' and 'Completed'

Thank you for your help.

import sys
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.authentication_context import AuthenticationContext

ONEDRIVE_BASE_URL = 'https://abc.sharepoint.com/'
ONEDRIVE_SITE = '/sites/glas'  # every share point has a home.
file_url = '/sites/glas/Shared Documents/Targeting/Bot_testing/Dis_Out/' 
siteurl = ONEDRIVE_BASE_URL + ONEDRIVE_SITE
ctx_auth = AuthenticationContext(url=ONEDRIVE_BASE_URL)
ctx_auth.acquire_token_for_user(user['username'],user['password'])
ctx = ClientContext(siteurl, ctx_auth)
source_file = ctx.web.get_folder_by_server_relative_url(file_url)
ctx.load(source_file)
ctx.execute_query()
files = source_file.files
ctx.load(files)
ctx.execute_query()

#download from share drive onto local folder
for myfile in files:
    try:
        print("File name: {0}".format(myfile.properties["Name"]))
        file_url = '/sites/glas/Shared Documents/Targeting/Bot_testing/Dis_Out' + myfile.properties["Name"]
    # print(file_url)
        ctx = ClientContext(siteurl, ctx_auth)
        source_file = ctx.web.get_file_by_server_relative_url(file_url)
        local_file_name = os.path.basename(file_url)
        local_file = open(local_file_name, "wb")
        source_file.download(local_file).execute_query()
        local_file.close()
0 Answers
Related