banner



Can Python Upload Files To Sharepoint

Past:   |   Updated: 2021-04-01   |   Comments (4)   |   Related: > SharePoint


Trouble

According to Microsoft, over 200,000 organizations and 190 1000000 people have SharePoint for intranets, team sites, and content direction (Microsoft, 2021). Nowadays, multiple versions of SharePoint are in utilize. Several open-source Python libraries tin interact with SharePoint. People may come across compatibility issues when running Python programs to handle files in SharePoint document libraries. These Python programs usually upload, download, delete, and search for documents. IT professionals must spend much time on a trial and error learning process to solve the compatibility issues. They desire to look at some sample programs and execute them in a complimentary trial environment to speed upwardly learning.

Solution

We first introduce the "Microsoft 365 Developer Program" that allows IT professionals to admission a SharePoint Online environment (Graham, 2019). People tin bring together the programme without a credit card and whatsoever payment (Microsoft 365, 2021). At the time of this writing, all participants can get a free Microsoft 365 E5 developer subscription. We then work on a fictitious project for a digital publishing platform, like MSSQLTips.com, and provide Python scripts to handle files in a SharePoint document library. We utilise the Python library "Office365-REST-Python-Client" (Gremyachev, 2020) to connect SharePoint document libraries. The official site of this Python library provides many useful sample scripts. We can practice these Python scripts in the trial environment too. The article comprises 2 parts, and readers who take an Function 365 environment tin can skip the kickoff part:

  • 1 – Creating a SharePoint Online Environment
  • 2 – Treatment Files in SharePoint Document Library

In the first part, we go through the steps to create an office 365 account and access a SharePoint Online environment. To simulate a small corporate environment, we install sample data packs. The "Users" sample data pack creates 16 fictitious users, and the SharePoint sample information pack tin add several SharePoint site templates. To permit Python programs to access SharePoint certificate libraries, we disable security defaults. Even so, at work, we should consult administrators to configure the security for Python program access.

The second office explores steps to establish a connection with a SharePoint document library using the Python library "Office365-REST-Python-Client ii.3.i." We then encompass the process to upload a document to a SharePoint certificate library and add the certificate's metadata. Next, we show steps to download and delete files from the library. The document library may have folders and sub-folders. We show a style of searching for files recursively. We also provide sample scripts to handle documents in sub-folders.

The author tested all the programs used in this commodity with Microsoft Visual Studio Customs 2019 and Python 3.seven (64-flake) on Windows x Habitation 10.0 <X64>. During testing, all the Python programs were connected to the SharePoint Online environment provided by the "Microsoft 365 Developer Programme." The web browser "Opera" was used to access the SharePoint document library.

ane – Creating a SharePoint Online Surroundings

An effective strategy to learn figurer skills is to larn past doing. During practicing, we may want to carve up our studying environments from working environments. This department creates a new environment (a sandbox) using no personal data except a prison cell phone number. We need a jail cell phone to receive a verification code when setting upward our Microsoft 365 programmer subscription. The Office 365 business relationship registration process needs an email account. We sign up for a personalized email at https://world wide web.postal service.com. We besides download the web browser "Opera" for accessing the information on the Internet.

1.i Creating a Microsoft Account

At the fourth dimension of this writing, we can admission the landing page of the Microsoft 365 Developer Program at https://developer.microsoft.com/en-united states of america/microsoft-365/dev-plan. Figure 1 illustrates the landing page.

microsoft 365

Effigy 1 The Landing page of the Microsoft 365 Developer Program

After clicking on the button "Join Now" on the landing page, nosotros are asked to sign in to microsoftonline.com, equally illustrated in Figure 2.

microsoft 365 sign in

Figure ii The Microsoft business relationship sign-in dialog

To create a new Microsoft account, nosotros click on the link button "Create ane!" The dialog for creating a Microsoft account appears, as shown in Figure iii. We enter an email address, click on the "Next" button, and then follow the instructions on the screens to complete the registration process. At the stop of this step, we should accept a Microsoft account.

microsoft 365 create account

Figure three The dialog to create a Microsoft account

1.2 Participating in the Microsoft 365 Developer Programme

We go dorsum to the Microsoft account sign-in folio, illustrated in Figure ii. Following the instructions on the screens, we sign into the Microsoft account. During the signing-in procedure, the program asks united states a few questions, as shown in Figure 4. Answer these questions and complete the class.

microsoft 365 create account

Effigy four Bring together the Microsoft 365 developer plan

We click on the button "Next" and follow instructions on the screens to consummate the signing-in process. Then, we arrive at the contour page, every bit shown in Figure 5.

microsoft 365 training

Figure v The profile page of the Microsoft Programmer Program

one.3Setting up an Office 365 Programmer Subscription

As illustrated in Effigy five, the Microsoft 365 developer program membership entitles us to a free Microsoft 365 E5 subscription with all Office 365 apps, including SharePoint, OneDrive, Outlook/Exchange, Teams, Planner, Word, Excel, PowerPoint, and more than (Microsoft 365, 2021). We use this subscription to build a SharePoint Online surroundings and run Python programs. Nosotros click on the "SET Upwards E5 SUBSCRIPTION" button on the spider web page to start the subscription process. A dialog appears, and it should look like Figure six.

microsoft 365 developer subscription

Effigy 6 Set up Microsoft 365 E5 developer subscription

Nosotros must select a country (or region), a username, a domain, and a password to complete the form. When the button "Continue" becomes enabled, we click on the button. The "Add together phone number for security" dialog appears, equally shown in Effigy 7. We should employ a valid cell phone number to receive a code. After we enter the code, the "Ready" push becomes enabled. We click on the button to proceed the sign-upwards process.

microsoft 365 developer subscription

Figure vii Add phone number for security

Nosotros follow instructions on the screens to complete the setup process. And then, we land on a dashboard page, as shown in Figure 8. The username and domain selected in Effigy 6 course the administrator business relationship. In the "Sample information packs" section, nosotros can choose to install sample data packs. The Users sample data pack creates sixteen fictitious users on the subscription, and the SharePoint sample data pack contains several site templates (Microsoft 365, 2021). We install the User data packs and a SharePoint team site template. The installation process may accept a few minutes.

microsoft 365 developer subscription

Effigy 8 A dashboard in the Microsoft 365 dev center

1.4 Turning off Security Defaults

By default, Microsoft automatically enforces a set of basic identity security mechanisms. To enable Python programs to access SharePoint sites, we disable the security defaults. However, at work, we should consult Role 365 administrators for any changes in security configurations. All configurations in this article are for demonstration. The goal is to show how to use Python scripts to handle files in a SharePoint certificate library. We present a quick and straightforward way to create a certificate library for Python applications to access. Nosotros should not utilise this method in product.

We use the following steps to turn off the security defaults. Start, let us sign into the site https://www.office.com/ using the ambassador account. Nosotros and so find the "App launcher" icon on the height left, as shown in Figure 9.  Clicking on the icon, nosotros see a list of Apps in a pop-upward pane. The "Admin" app icon appears in the pane. Alternatively, we can detect the "Admin" app icon in the vertical toolbar on the left.

office 365 admin center

Figure 9 Click on the App launcher icon to show some frequently used Microsoft Apps

Clicking on the "Admin" icon, we land on the "Microsoft 365 admin center" folio, every bit shown in Figure x. We can expand the User carte du jour to view the 16 fictitious users. We expect to find the "Azure Active Directory" menu item, but information technology is not visible. Clicking on the "Show all" button, we come across a complete list of menu items.

office 365 admin center

Figure 10 The landing page of the Microsoft 365 admin centre

After clicking on the "Evidence all" button, we expand the left pane and see the "Azure Agile Directo…" menu detail, as shown in Figure eleven.

office 365 admin center

Figure xi Expand the admin centers

When we click on the "Azure Active Directo…" menu item, a pop-up dialog shows up, every bit shown in Effigy 12.

office 365 admin center

Effigy 12 Use ambassador account to log in Microsoft Azure

We select the administrator business relationship to access the "Azure Agile Directory admin middle," and the landing page should await like Effigy thirteen. On the left pane, in that location is an "Azure Active Directory" link button.

azure active directory admin center

Figure 13 Azure Active Directory admin heart

We click on the link button "Azure Active Directory," and then choose the "Properties" menu item. The "Manage Security defaults" link button appears, as shown in Effigy 14. Clicking on the button, we can disable the security defaults on the right pane. Finally, we click on the "Salve" button to save the alter. We want to emphasize again that we should consult Part 365 administrators for any security configuration changes. This article introduces a quick way, merely non a very practical one, to give access to Python applications.

azure active directory admin center

Figure fourteen The process to disable security defaults

i.5 Creating a SharePoint Document Library

SharePoint is a website-based collaboration system that empowers business teams to piece of work together and implement business concern process automation (Satapathi, 2020). A fictitious company ABC provides a digital publishing platform for writers. The company wants to utilise a SharePoint document library to manage articles and some corporate documents. After writers submit their manufactures through a web form, A Python program moves the articles to the SharePoint document library. And so, ABC editors review these manufactures. If articles do not fit the platform, the editors tag the articles with the "Rejected" label. Otherwise, the editors put the "Approved" label on the manufactures. Then, another Python program carries these articles to a file server for publication. The programme places corporate documents in a sub-folder of the document library.

To create a SharePoint document library for the company ABC, nosotros commencement demand to build a SharePoint site. If we sign out of the site https://www.office.com/, we demand to sign in again with the ambassador'due south business relationship. We click on the "App launcher" icon. On the pop-up pane shown in Figure 9, we select the "SharePoint" app. We then country on a page shown in Figure 15. The "Create site" button on this folio allows u.s.a. to create a SharePoint site using the installed site templates. Microsoft provides SharePoint Online training tutorial: Create a site in SharePoint. Following their instructions, we create a SharePoint site, "ABC," and add a "Publications" document library.

create sharepoint site

Figure xv Create a SharePoint Site

We add two columns to the library: Category and Status. The Category column is a gratuitous form text field. A writer can make up one's mind a category for his/her article during uploading process. Editors tin recommend a category for an article. The Status column is a choice cavalcade with four options: Submitted, In Process, Rejected, and Approved. The default value of the choice cavalcade is "Submitted." After completing the setup, nosotros upload a certificate to test the library. The certificate library should look like Figure xvi. In the next department, nosotros utilise Python scripts to upload, download, and delete documents. That department as well covers steps to add together values to the Category column, create a folder and handle files in the binder.

create sharepoint site

Figure 16 The SharePoint library with ane certificate

2 – Handling Files in the SharePoint Document Library

At the ABC company, nosotros apply a Python programme to movement the uploaded files from a webserver to the SharePoint certificate library. After editors review articles and determine to publish them, nosotros apply some other Python program to move the latest versions of the files from the document library to a file server. We also use Python code to upload some corporate documents to a sub-folder of the library. During evolution, we created a Python application project using Visual 2019 (Zhou, 2020). We create a virtual surroundings for this project using this requirement.txt:

certifi==2020.12.five cffi==i.14.five chardet==4.0.0 cryptography==three.iv.vi idna==two.10 msal==1.10.0 Office365-Residue-Python-Client==ii.3.i pip==21.0.1 pycparser==two.twenty PyJWT==2.0.i requests==2.25.1 setuptools==54.one.ane urllib3==one.26.iii          

The Python library "Office365-REST-Python-Customer" comes with many examples, and we can study these examples at https://github.com/vgrem/Office365-REST-Python-Client/tree/master/examples/sharepoint. These examples cover virtually business requirements we may encounter at work. If we cannot discover detailed information about a class or a method, we can view the source code at https://github.com/vgrem/Office365-REST-Python-Customer/tree/primary/office365/sharepoint. These Python scripts are also useful resources for the states to written report Python programming. In situation where some operations, for example, upload and download documents are used repeatedly in a projection, it is good idea to create helper methods for them.

two.1 Connecting to the SharePoint Library

A certificate library is a special blazon of SharePoint list that contains documents and metadata (Katzer & Crawford, 2013). Nosotros can use the Python library "Office365-Residuum-Python-Client" to construct a file object or a list item object. The file object has a property "listItemAllFields" representing the corresponding list item. Besides, the list item has a property "file" that allows us to admission the associated file object. Since we created the document library and uploaded a file to the library already, we now use the following Python code to connect the SharePoint library, list all files, and admission metadata through their associated list detail properties:

            from            office365            .            sharepoint            .            client_context            import            ClientContext            SP_SITE_URL =            'https://trainingcenter2021.sharepoint.com/sites/ABC/'            SP_DOC_LIBRARY =            'Publications'            USERNAME =            'sptraining@trainingcenter2021.onmicrosoft.com'            Countersign =            '******'            # 1. Create a ClientContext object and use the user's credentials for authentication            ctx =            ClientContext            (SP_SITE_URL).with_user_credentials(USERNAME, Password)            # 2. Read file entities from the SharePoint certificate library            files = ctx.spider web.lists.get_by_title(SP_DOC_LIBRARY).root_folder.files            ctx.load(files)            ctx.execute_query()            # 3. loop through file entities            for                          file            in                          files:                          # 4. Access the file object properties                          impress(file.backdrop[            'Name'            ], file.properties[            'UniqueId'            ])                          # 5. Admission list item object through the file object                          item = file.listItemAllFields                          ctx.load(item)                          ctx.execute_query()                          print(            'Access metadata - Category: {0}, Status: {1}'            .format(item.properties[            'Category'            ], item.properties[            'Status'            ]))            # four. The Output:            # File Handling in SharePoint Certificate Library Using Python.docx 77819f08-5fbe-450f-9f9b-d3ae2862cbb5            # Admission metadata - Category: Python, Status: Submitted          

As same, a certificate library is a special blazon of SharePoint list. We also tin can find all list items in the library then access the associated file objects. Like the preceding Python code block, nosotros create a "ClientContext" object to represent the target SharePoint resources and apply the user credentials for hallmark. Then, the Python code retrieves a SharePoint list from the document library. A list item has an associated file object; therefore, nosotros tin can access all documents in a library by accessing all the list items.

            from            urllib            import            parse            from            office365            .            sharepoint            .            client_context            import            ClientContext            SP_SITE_URL =            'https://trainingcenter2021.sharepoint.com/sites/ABC/'            SP_DOC_LIBRARY =            'Publications'            USERNAME =            'sptraining@trainingcenter2021.onmicrosoft.com'            Password =            '******'            # i. Create a ClientContext object and apply the user'due south credentials for authentication            ctx =            ClientContext            (SP_SITE_URL).with_user_credentials(USERNAME, Countersign)            # 2. Call up a SharePoint list from the document library            oList = ctx.spider web.lists.get_by_title(SP_DOC_LIBRARY)            items = oList.items            ctx.load(items)            ctx.execute_query()            # iii. Look through list items            for                          detail            in                          items:                          # 4. Admission list item backdrop. Parse file unique Id from the ServerRedirectedEmbedUri holding of the listing item                          dic_query_string =            parse            .parse_qs(            parse            .urlsplit(item.properties[            'ServerRedirectedEmbedUri'            ]).query)                          unique_id = dic_query_string[            'sourcedoc'            ][0][i:-1]                          impress(            'Unique Id:{0}, Category: {1}, Status: {two}'            .format(unique_id, item.properties[            'Category'            ], item.properties[            'Status'            ]))                          # five. Remember the file object from the list item                          file = item.file                          ctx.load(file)                          ctx.execute_query()                          print(            'Unique Id:{0}, Proper name: {1}'            .format(file.properties[            'UniqueId'            ], file.backdrop[            'Name'            ]))            # 6. The output:            #Unique Id:77819f08-5fbe-450f-9f9b-d3ae2862cbb5, Category: Python, Status: Submitted            #Unique Id:77819f08-5fbe-450f-9f9b-d3ae2862cbb5, Name: File Treatment in SharePoint Certificate Library Using Python.docx          

We ordinarily identify all settings in a standalone configure file. Gremyachev gives an example of a setting file. We tin also use Python ConfigParser to read configuration data from a file with a structure like Microsoft Windows INI files (Bodnar, 2020). Another method is to place the configuration information in a JSON file (TutsWiki, 2020). However, the code we presented here did not apply any of these methods merely put all Python statements in a unmarried file. This coding manner is for demonstration, and nosotros should not employ this style in actual development.

2.ii Uploading Files to the Document Library

When a writer uploads his/her article to ABC company, the writer chooses the category "R Language" for the article. The spider web application places the article on the webserver. A Python program should ship this file to the SharePoint library and tag this commodity with the category "R Language." The program shown in the following code block implements these steps.

            import            bone            from            office365            .            sharepoint            .            client_context            import            ClientContext            from            office365            .            sharepoint            .            listitems            .            caml            .            caml_query            import            CamlQuery            SP_SITE_URL =            'https://trainingcenter2021.sharepoint.com/sites/ABC/'            SP_DOC_LIBRARY =            'Publications'            USERNAME =            'sptraining@trainingcenter2021.onmicrosoft.com'            Password =            '******'            # Assuming the file path on the webserver            file_path =            "C:/temp/manufactures/Index Numbers Explained with Examples in R.docx"            file_name =            os            .            path            .basename(file_path)            # one. Create a ClientContext object and utilize the user's credentials for authentication            ctx =            ClientContext            (SP_SITE_URL).with_user_credentials(USERNAME, Countersign)            # two. Read the content of the file            with                          open(file_path,            'rb'            )            as                          file_obj:                          file_content = file_obj.read()            # 3. Upload the content to the SharePoint document library            sp_folder = ctx.web.lists.get_by_title(SP_DOC_LIBRARY).root_folder            sp_file = sp_folder.upload_file(file_name, file_content)            ctx.execute_query()            # iv. Add metadata to the document by assigning a value to the Category belongings            item = sp_file.listItemAllFields            particular.set_property(            "Category"            ,            "R Language"            )            item.update()            ctx.execute_batch()          

We execute the code through Studio 2019 and and then cheque the certificate library using the "Opera." The document "Index Numbers Explained with Examples in R.docx" should be added to the library. The Status cavalcade shows the default value "Submitted," and the Category column of the document should accept a value of "R Language," as shown in Effigy 17.

publications

Figure 17 Update Metadata of a file in the SharePoint library

2.3 Downloading Files from the Certificate Library

At the company ABC, the editors review articles and correct spelling, punctuation, and grammatical errors. When they work on an article in the document library, they change the article status from "Submitted" to "In Process." So, they may change the condition to "Approved" or "Rejected" when they complete reviewing. Adjacent, a Python program moves the approved article to a file server for publication. The programme showtime searches all articles with status "Canonical" status. And then, the program downloads all these manufactures to the file server. The post-obit Python code implements these steps.

            import            os            from            office365            .            sharepoint            .            client_context            import            ClientContext            from            office365            .            sharepoint            .            listitems            .            caml            .            caml_query            import            CamlQuery            from            office365            .            sharepoint            .            files            .            file            import            File            SP_SITE_URL =            'https://trainingcenter2021.sharepoint.com/sites/ABC/'            SP_DOC_LIBRARY =            'Publications'            USERNAME =            'sptraining@trainingcenter2021.onmicrosoft.com'            PASSWORD =            '******'            FILE_SERVER_PATH =            "C:/temp/publications/"            # 1. Create a ClientContext object to connect the certificate library            ctx =            ClientContext            (SP_SITE_URL).with_user_credentials(USERNAME, Password)            # 2. Build a CAML query to find all list items that associate the approved articles            qry_text =            '''<Where>                            <Eq>                               <FieldRef Name='Condition'/>                               <Value Blazon='Text'>Approved</Value>                            </Eq>                         </Where>'''            caml_query =            CamlQuery            .parse(qry_text)            caml_query.FolderServerRelativeUrl = SP_DOC_LIBRARY            # iii. Recollect list items based on the CAML query            oList = ctx.web.lists.get_by_title(SP_DOC_LIBRARY)            items = oList.get_items(caml_query)            ctx.execute_query()            # 4. Loop through all list items            for                          item            in                          items:                          # v. Query the SharePoint document library to notice the associated file of a listing item                          file = item.file                          ctx.load(file)                          ctx.execute_query()                          # vi. Construct the file path on the file server                          download_file_path =            os            .            path            .join(FILE_SERVER_PATH, file.properties[            'Name'            ])                          # 7. Download file from the certificate library to the file server                          with                          open(download_file_path,            'wb'            )            as                          download_file:                          download_file.write(file.read())                          impress(            'File downloaded :{0}'            .format(download_file_path))          

The lawmaking block also shows the CAML syntax. The Collaborative Application Markup Language (CAML), an XML-based language, can query a SharePoint list (McCarthy, 2017). In the preceding code block, the simple CAML query definition defines a filter where the column field equals a value of "Approved" using the "Eq" chemical element. We also tin employ CAML to customize SharePoint sites (Juvonen & Caputo, 2014).

ii.4 Deleting Files from the Document Library

The ABC company does not want to maintain the rejected manufactures. The company uses a Python programme to remove these files from the document library. Similar to the downloading process, the deleting process searches for all articles with the condition "Rejected." So, the program deletes all these manufactures.

            from            office365            .            sharepoint            .            client_context            import            ClientContext            from            office365            .            sharepoint            .            listitems            .            caml            .            caml_query            import            CamlQuery            from            office365            .            sharepoint            .            files            .            file            import            File            SP_SITE_URL =            'https://trainingcenter2021.sharepoint.com/sites/ABC/'            SP_DOC_LIBRARY =            'Publications'            USERNAME =            'sptraining@trainingcenter2021.onmicrosoft.com'            PASSWORD =            '******'            # 1. Create a ClientContext object to connect the document library            ctx =            ClientContext            (SP_SITE_URL).with_user_credentials(USERNAME, Countersign)            # two Build a CAML query to find all list items that associate the rejected manufactures            qry_text =            '''<Where>                            <Eq>                               <FieldRef Name='Status'/>                               <Value Type='Text'>Rejected</Value>                            </Eq>                          </Where>'''            caml_query =            CamlQuery            .parse(qry_text)            caml_query.FolderServerRelativeUrl = SP_DOC_LIBRARY                        # iii Retrieve listing items based on the CAML query            oList = ctx.web.lists.get_by_title(SP_DOC_LIBRARY)            items = oList.get_items(caml_query)            ctx.execute_query()            # 4 Loop through all list items            for                          item            in                          items:                          # 5 Query the SharePoint certificate library to notice the associated file                          file = item.file                          ctx.load(file)                          ctx.execute_query()                          # 6 Invoke the delete_object method to delete the file                                                  file.delete_object()                          ctx.execute_query()                          print(            'File deleted :{0}'            .format(file.backdrop[            'Name'            ]))          

two.5 Treatment Files in SharePoint Document Library Folders

A document library may comprise folders, which are similar to folders in the Windows File Arrangement. To organize corporate documents, the ABC visitor wants to group various documents in unlike folders. In preceding sections, when we uploaded files to the Publication library, the files went to the root binder. We can create folders inside the root folder. These folders may have independent permissions.

2.5.1 Uploading Files to the Document Library Folder

The following Python code accesses the binder "Administrator" in the SharePoint library. If the binder does not exist, the programme is going to create it. The Python library "Office365-REST-Python-Client" provides a folder class to represent a SharePoint folder. We use the folder object's upload file method to upload file content.

            import            os            from            office365            .            sharepoint            .            client_context            import            ClientContext            from            office365            .            sharepoint            .            listitems            .            caml            .            caml_query            import            CamlQuery            SP_SITE_URL =            'https://trainingcenter2021.sharepoint.com/sites/ABC/'            SP_DOC_LIBRARY =            'Publications'            SP_DOC_LIBRARY_FOLDER =            'Administrator'                                    # The folder in the document library            USERNAME =            'sptraining@trainingcenter2021.onmicrosoft.com'            Countersign =            '******'            # 1. Assuming the location of the uploading file            file_path =            "C:/temp/administration/Request Form2.docx"            file_name =            os            .            path            .basename(file_path)            # 2. Create a ClientContext object to access the SharePoint library            ctx =            ClientContext            (SP_SITE_URL).with_user_credentials(USERNAME, PASSWORD)            # 3. Access the SharePoint binder or create the folder if it doesn't exist            sp_folder_path =            "/{0}/{1}"            .format(SP_DOC_LIBRARY,SP_DOC_LIBRARY_FOLDER)            sp_folder  =              ctx.web.ensure_folder_path(sp_folder_path).execute_query()            # four. Read the content of the file            with                          open(file_path,            'rb'            )            every bit                          file_obj:                          file_content = file_obj.read()            # 5. Upload the file to the folder in the SharePoint library            sp_file = sp_folder.upload_file(file_name, file_content)            ctx.execute_query()            # half-dozen. Add metadata to the uploaded certificate            item = sp_file.listItemAllFields            detail.set_property(            "Category"            ,            "Form"            )            item.update()            ctx.execute_batch()          

2.5.ii Downloading Files from the Certificate Library Folder

We desire to download all forms (files marked with Category "Form") in the Administrator folder. We first create a folder object to represent the document library folder. The binder object tells united states of america the folder's relative URL in SharePoint Online. A CAML query so uses this URL to find all files in the folder. Adjacent, nosotros download the file to the file server.

            import            os            from            office365            .            sharepoint            .            client_context            import            ClientContext            from            office365            .            sharepoint            .            listitems            .            caml            .            caml_query            import            CamlQuery            from            office365            .            sharepoint            .            files            .            file            import            File            SP_SITE_URL =            'https://trainingcenter2021.sharepoint.com/sites/ABC/'            SP_DOC_LIBRARY =            'Publications'            SP_DOC_LIBRARY_FOLDER =            'Administrator'                                    # The folder in the document library            USERNAME =            'sptraining@trainingcenter2021.onmicrosoft.com'            PASSWORD  =            '******'            FILE_SERVER_PATH =            "C:/temp/forms/"            # 1. Create a ClientContext object to connect the certificate library            ctx =            ClientContext            (SP_SITE_URL).with_user_credentials(USERNAME, Password)            # two. Connect to the SharePoint folder and construct a SharePoint folder object            sp_folder_path =            "/{0}/{ane}"            .format(SP_DOC_LIBRARY,SP_DOC_LIBRARY_FOLDER)            sp_folder =             ctx.spider web.ensure_folder_path(sp_folder_path).execute_query()            # 3. Build a CAML query to detect all list items that are in the "Class" category            qry_text =            '''<Where>                            <Eq>                               <FieldRef Name='Category'/>                               <Value Blazon='Text'>Form</Value>                            </Eq>                          </Where>'''            caml_query =            CamlQuery            .parse(qry_text)            caml_query.FolderServerRelativeUrl = sp_folder.backdrop[            'ServerRelativeUrl'            ]            # iv. Retrieve all list items based on the CAML query            oList = ctx.web.lists.get_by_title(SP_DOC_LIBRARY)            items = oList.get_items(caml_query)            ctx.execute_query()            # 5. Loop through all list items            for                          detail            in                          items:                          # vi. Query the SharePoint document library to discover the associated file                          file = item.file                          ctx.load(file)                          ctx.execute_query()                          # vii. Construct the file path on the file server                          download_file_path =            os            .            path            .join(FILE_SERVER_PATH, file.backdrop[            'Name'            ])                          # viii. Download the file from the certificate library binder                          with                          open(download_file_path,            'wb'            )            as                          download_file:                   download_file.write(file.read())                          print(            'File downloaded :{0}'            .format(file.backdrop[            'Name'            ]))          

2.5.three Deleting Files from the Document Library Binder

To delete a file from the document library folder, we should get-go notice the list item that contains the file. From the listing item, we can construct a file object that provides a delete object method. Next, nosotros invoke the delete method to remove the file from the folder. The following code deletes all forms from the library.

            import            os            from            office365            .            sharepoint            .            client_context            import            ClientContext            from            office365            .            sharepoint            .            listitems            .            caml            .            caml_query            import            CamlQuery            from            office365            .            sharepoint            .            files            .            file            import            File            SP_SITE_URL =            'https://trainingcenter2021.sharepoint.com/sites/ABC/'            SP_DOC_LIBRARY =            'Publications'            SP_DOC_LIBRARY_FOLDER =            'Administrator'            USERNAME =            'sptraining@trainingcenter2021.onmicrosoft.com'            PASSWORD =            '******'            # one. Create a ClientContext object to connect the certificate library            ctx =            ClientContext            (SP_SITE_URL).with_user_credentials(USERNAME, Password)            # two. Construct a SharePoint folder object            sp_folder_path =            "/{0}/{i}"            .format(SP_DOC_LIBRARY,SP_DOC_LIBRARY_FOLDER)            sp_folder =              ctx.web.ensure_folder_path(sp_folder_path).execute_query()            # 3. Build a CAML query to find all listing items that associate to the grade            qry_text =            '''<Where>                            <Eq>                               <FieldRef Proper name='Category'/>                               <Value Type='Text'>Form</Value>                            </Eq>                          </Where>'''            caml_query =            CamlQuery            .parse(qry_text)            caml_query.FolderServerRelativeUrl = sp_folder.properties[            'ServerRelativeUrl'            ]            # iv. Remember all list items based on the CAML query            oList = ctx.web.lists.get_by_title(SP_DOC_LIBRARY)            items = oList.get_items(caml_query)            ctx.execute_query()            # 5. Loop through all list items            for                          item            in                          items:                          # half-dozen. Query the SharePoint document library to construct a file object                          file = item.file                          ctx.load(file)                          ctx.execute_query()                          # vii. Invoke the delete_object method to delete the file                          file.delete_object()                          ctx.execute_query()                          print(            'File deleted :{0}'            .format(file.properties[            "ServerRelativeUrl"            ]))          

ii.5.4 Searching for Files in the Document Library Recursively

The ABC company may demand to find all files being in the category "Approved." Since a document library has folders, and the folders may have sub-folders, the program should search for files recursively. When amalgam a CAML query, we tin can specify the telescopic for returning listing items and list folders. When we pass the scope "ViewScope.Recursive" to the CamlQuery.parse() function, the function searches for files that satisfy the query in all folders.

            from            office365            .            sharepoint            .            client_context            import            ClientContext            from            office365            .            sharepoint            .            listitems            .            caml            .            caml_query            import            CamlQuery            ,            ViewScope            SP_SITE_URL =            'https://trainingcenter2021.sharepoint.com/sites/ABC/'            SP_DOC_LIBRARY =            'Publications'            USERNAME =            'sptraining@trainingcenter2021.onmicrosoft.com'            PASSWORD =            '******'                        # 1. Create a ClientContext object to connect the document library            ctx =            ClientContext            (SP_SITE_URL).with_user_credentials(USERNAME, PASSWORD)            # 2. Build a CAML query to notice all listing items being in the category "Canonical"            qry_text =            '''             <Where>                                               <Eq>                                       <FieldRef Proper noun='Status'/>                                       <Value Type='Text'>Canonical</Value>                                   </Eq>                                                 </Where>'''            # three. Ascertain the scope "Recursive" that search for files in all the folders.            caml_query =            CamlQuery            .parse(qry_text,            ViewScope            .Recursive)            caml_query.FolderServerRelativeUrl = SP_DOC_LIBRARY            # iv. Retrieve listing items based on the CAML query            oList = ctx.web.lists.get_by_title(SP_DOC_LIBRARY)            items = oList.get_items(caml_query)            ctx.execute_query()            # 5. Loop through all list items            for                          item            in                          items:                          # 6. Query the SharePoint document library to observe the associated file                          file = item.file                          ctx.load(file)                          ctx.execute_query()                          # seven. Notice the Server Relative URL of the file                          file_relative_url =file.backdrop[            "ServerRelativeUrl"            ]                          # 8. Print the Relative URL of the file                          print(            'Relative File Path: {0}'            .format(file_relative_url))          

Summary

The article demonstrated how to set up a SharePoint Online environment and create a SharePoint document library. We and then used Python scripts to handle files in the certificate library. These scripts also showed that the document library is a SharePoint list. To show how to employ these scripts at work, we assumed a fictitious project that enabled business process automation for a digital publishing platform. We provided a proof-of-concept solution to the project.

Nosotros covered steps to create a Microsoft account, participate in the Microsoft 365 Programmer Program, ready an Role 365 Developer subscription, and create a SharePoint site. For the sake of demonstration and simplicity, we turned off security so that Python programs could access the SharePoint site. We too installed sample data packs and then that users could practice Python scripts in a minor corporate environment. The article explored a few steps to add a SharePoint certificate library to the SharePoint site.

Next, the article showed how to connect to the SharePoint document library, upload files to the library, and download and delete files from the library. The Python programs provided a fashion of adding metadata to an uploaded document. Nosotros likewise demonstrated techniques to access SharePoint certificate library folders and handle files in the folders. The last piece of the Python code could search for files in the document library recursively.

Reference

Bodnar, J. (2020). Python ConfigParser tutorial. https://zetcode.com/python/configparser/.

Graham, L. (2019). Microsoft 365 Programmer Programme FAQ. https://docs.microsoft.com/en-u.s.a./function/developer-programme/microsoft-365-developer-program-faq.

Juvonen, 5. & Caputo, L. (2014). Introduction to Collaborative Application Markup Language (CAML). https://docs.microsoft.com/en-the states/sharepoint/dev/schema/introduction-to-collaborative-application-markup-language-caml.

Katzer, 1000. & Crawford, D. (2013). Office 365: Migrating and Managing Your Business in the Deject. Apress

McCarthy, C. (2017). Learn to Use CAML Query – Office 1. https://world wide web.brightwork.com/blog/caml-joins-caml-syntax-brightwork.

Microsoft (2021). SharePoint. https://www.microsoft.com/en-ca/microsoft-365/sharepoint/collaboration/.

Microsoft 365 (2021). Join the Microsoft 365 Programmer Program today! https://programmer.microsoft.com/en-united states of america/microsoft-365/dev-programme.

Gremyachev, V. (2020). Office365-REST-Python-Client ii.three.1. https://pypi.org/project/Office365-REST-Python-Client/

Zhou, N. (2020). Learning Python in Visual Studio 2019. /sqlservertip/6442/learning-python-in-visual-studio-2019/.

Chan, E. (2013). Scopes in a CAML Query. http://www.codegrimoire.com/2013/08/scopes-in-caml-query.html.

Satapathi, S. (2020). Performing A CRUD Operation On A SharePoint List Using Python. https://world wide web.c-sharpcorner.com/article/performing-crud-operation-on-sharepoint-list-using-python/.

TutsWiki (2020). WRITING AND READING JSON CONFIG FILE IN PYTHON. https://tutswiki.com/read-write-json-config-file-in-python/

Adjacent Steps
  • In this commodity, the author disabled the security defaults so that Python programs could access the SharePoint library. Nosotros should consult Function 365 administrators to work out a security solution for the workplaces. The coding style in this article is for demonstration. Nosotros should non use this fashion at work. Lu provides a solution to upload files to Microsoft 365 SharePoint. Fifty-fifty though Lu used some other open-source Python library, "SharePlum," his sample code is well-structured. He put all configurations into a JSON file, and he also adopted the object-oriented programming approach. We can observe his YouTube video at https://youtu.be/BV6SLhOF3zU.
  • Bank check out these related tips:
    • Create a Python Django Website with a SQL Server Database
    • CRUD Operations in SQL Server using Python
    • Learning Python in Visual Studio 2019
    • Python Programming Tutorial with Top-Down Approach
    • Recursive Programming Techniques using Python
    • Reading SharePoint Lists with Integration Services 2017
    • What is Microsoft Power Apps

Related Manufactures

Popular Articles

Nigh the writer

MSSQLTips author Nai Biao Zhou Nai Biao Zhou is a Senior Software Developer with 20+ years of feel in software development, specializing in Data Warehousing, Business concern Intelligence, Data Mining and solution architecture design.

View all my tips

Article Terminal Updated: 2021-04-01

Can Python Upload Files To Sharepoint,

Source: https://www.mssqltips.com/sqlservertip/6799/file-handling-sharepoint-document-library-python/

Posted by: rodgersimas1998.blogspot.com

0 Response to "Can Python Upload Files To Sharepoint"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel