I am trying to use Python to upload a file from my local drive to a SharePoint document library.
I customized established code, but I am receiving a TypeError that I cannot resolve.
I have adapted the below code from here.
=====================================
import os
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.client_credential import ClientCredential
CLIENT_ID = "my-client-id"
CLIENT_SECRET = "my-secret"
#Create a ClientCredential object
client_credential = ClientCredential(CLIENT_ID, CLIENT_SECRET)
#Create a ClientContext object for the SharePoint site
ctx = ClientContext("https://MySharePointURL.sharepoint.com").with_credentials(client_credential)
target_url = "/sites/mor_data_work/mor_data_work_doc_lib"
target_folder = ctx.web.get_folder_by_server_relative_url(target_url)
size_chunk = 1000000
local_path = os.path.abspath(file_name) ### "file_name" is a variable established earlier that is a string in the format "some_file_name.csv"
#local_path = "../../../tests/data/SharePoint User Guide.docx"
def print_upload_progress(offset):
file_size = os.path.getsize(local_path)
print("Uploaded '{0}' bytes from '{1}'...[{2}%]".format(offset, file_size, round(offset / file_size * 100, 2)))
with open(local_path, 'rb') as f:
uploaded_file = target_folder.files.create_upload_session(f, size_chunk,
print_upload_progress).execute_query()
print('File {0} has been uploaded successfully'.format(uploaded_file.serverRelativeUrl))
===================================
And, this is the error I am receiving:
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5436/2516037777.py in <module>
28
29 with open(local_path, 'rb') as f:
---> 30 uploaded_file = target_folder.files.create_upload_session(f, size_chunk,
31 print_upload_progress).execute_query()
32
~\anaconda3\lib\site-packages\office365\sharepoint\files\file_collection.py in create_upload_session(self, source_path, chunk_size, chunk_uploaded, *chunk_func_args)
44 :return: office365.sharepoint.files.file.File
45 """
---> 46 file_size = os.path.getsize(source_path)
47 if file_size > chunk_size:
48 qry = UploadSessionQuery(self, source_path, chunk_size, chunk_uploaded, chunk_func_args)
~\anaconda3\lib\genericpath.py in getsize(filename)
48 def getsize(filename):
49 """Return the size of a file, reported by os.stat()."""
---> 50 return os.stat(filename).st_size
51
52
TypeError: stat: path should be string, bytes, os.PathLike or integer, not BufferedReader
===================================
Anyone have thoughts about that error or anything else that looks wrong in there?