Copy file in Sharepoint using Office365-REST-Python-Client

Question:

I’m using this nice tool, based at this github link.

As in the title, how can I copy a file from one SharePoint folder to another?
I cannot find any example in the official documentation.

thank you!

Asked By: Vincenzo Lavorini

||

Answers:

SharePoint has a CreateCopyJobs API which you can leverage to copy or move the files. See the linked blog for more details.

https://blog.velingeorgiev.com/createcopyjobs-api-copy-move-SharePoint-files-folders

It is possible to construct the REST queries to achieve this, doing something similar to the below.

import json
from office365.runtime.auth.user_credential import UserCredential
from office365.runtime.http.request_options import RequestOptions
from office365.sharepoint.client_context import ClientContext
from office365.runtime.http.http_method import HttpMethod
site_url = "https://{your-tenant-prefix}.sharepoint.com"


client = ClientContext("site_url").with_credentials(UserCredential("{username}", "{password}"))
request = RequestOptions("{0}/sites/_api/site/CreateCopyJobs".format(site_url))
request.method = HttpMethod.Post
request.data = { 
    "exportObjectUris":[ 
    "https://{your-tenant-prefix}.sharepoint.com/sites/site1/Shared%20Documents/Test.docx"
    ],
    "destinationUri":"https://{your-tenant-prefix}.sharepoint.com/sites/site2/Shared%20Documents",
    "options":{ 
    "IgnoreVersionHistory":true,
    "IsMoveMode":false
    }
}
response = client.execute_request_direct(request)

response.raise_for_status()
output = json.loads(response.content)
output = output['d']

Answered By: ayodele

The following codes could be used to copy the file called Test.txt from one folder to another.

source_file_url = '/sites/<site name>/Shared Documents/<source folder name>/Test.txt'
source_file = client_context.web.get_file_by_server_relative_url(source_file_url)

target_file_url = '/sites/<site name>/Shared Documents/<target folder name>/Test.txt'

source_file.copyto(target_file_url, True).get().execute_query()

Please let me know if you have questions.

Answered By: PatrickPan2018

PatrickPan2018’s answer works great with python REST Office365

Answered By: Dan Bean
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.