I'm trying to perform an upload files from Linux to SharePoint using Python. However, I tried a lot by googling but nothing help. At last, I got a PowerShell script that is working. So requesting help to convert the below script to Python 3

Specify tenant admin and site URL
$User = "[email protected]"
$SiteURL = "https://test-my.sharepoint.com/personal/justin_jacob_spidersoftin";

$Folder = "C:\Users\justin.jacob\Desktop\New folder"
$DocLibName = "Documents"

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$Password  = ConvertTo-SecureString ‘123@123’ -AsPlainText -Force

#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)

$Context.Credentials = $Creds

#Retrieve list
$List = $Context.Web.Lists.GetByTitle("$DocLibName")



#Upload file
Foreach ($File in (dir $Folder -File)) {
    $FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.ContentStream = $FileStream
    $FileCreationInfo.URL = $File
    $Upload = $List.RootFolder.Files.Add($FileCreationInfo)

1 Answer 1


You may take a reference of below demo about how to upload files in a directory:

for root, dirs, files in os.walk(r"D:\d365\SDK\SampleCode\JS\SOAPForJScript\SOAPForJScript"): 
for file in files:
    filepath = os.path.join(root, file)

    # perform the actual upload
    with open(filepath, 'rb+') as file_input:
            spfolder.upload_file(file_input, file)
        except Exception as err: 
            print("Some error occurred: " + str(err))

Complete demo:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.