0

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?

drewc
  • 1
  • 2
  • When you do it with the `local_path = "../../../tests/data/big_buck_bunny.mp4"` it works OK? – Jesus Fung Jun 05 '23 at 21:50
  • I didn't actually try with that test file, but this is the local_path I'm using: `C:\\Users\\admin\\My Drive\\data\\mor\\NEW_MOR\\mor_weekly_home_page_data.csv` Do I need to format that differently? Or are you seeing something else there? – drewc Jun 05 '23 at 21:58
  • can you provide the `value` of `file_name` and then `local_path` ? – Jesus Fung Jun 05 '23 at 22:12
  • `file_name` = 'mor_weekly_home_page_data.csv' `local_path` = 'C:\\Users\\admin\\My Drive\\data\\mor\\NEW_MOR\\mor_weekly_home_page_data.csv' – drewc Jun 05 '23 at 22:25
  • so the file 'mor_weekly_home_page_data.csv' is the same folder of the python file or where is it located from the python file perspective? – Jesus Fung Jun 05 '23 at 23:08
  • It is in the same folder as the Python file (which is a Jupyer notebook). – drewc Jun 05 '23 at 23:10

1 Answers1

0

Based on the answered questions, if the files will be in the same folder, I believe that if you do with open(file_name, 'rb') as f: instead of using local_path it should work.

If it doesn't solve the issue, you could try:

script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt" # --> replace with the relative path of the file you are looking for
abs_file_path = os.path.join(script_dir, rel_path)
with open(abs_file_path, 'rb') as f:
    uploaded_file = target_folder.files.create_upload_session(f, size_chunk,
                                              

            print_upload_progress).execute_query()

ref: https://stackoverflow.com/a/7166139/11897778

Jesus Fung
  • 76
  • 8
  • When I try the first option, I get the exact same error I was getting before. I'm a little confused about the 2nd option: Should I replace `file` with `file_name` and `"2091/data.txt"` with `"/mor_weekly_home_page_data.csv"`? – drewc Jun 06 '23 at 01:47
  • for 2nd option: do not replace `__file__`. For the `"2091/data.txt"` you replace it with "/mor_weekly_home_page_data.csv" or try without the slash so `"mor_weekly_home_page_data.csv"` (which i think this last one will work) – Jesus Fung Jun 06 '23 at 05:19
  • Okay, I tried it with and without the slash and got the same error both times: `---> 33 script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in` `NameError: name '__file__' is not defined` I don't know if this matters, but I'm running this in a Jupyer notebook. – drewc Jun 06 '23 at 15:02
  • Any other thoughts about that? – drewc Jun 08 '23 at 12:35
  • Okay, one small bit of progress: I figure out that since I'm running this in a Jupyter Notebook I need to put `__file__` in quotes like this: `("__file__")`. So, that resolved that issue, but now I'm back to getting the same error from the original post: `TypeError: stat: path should be string, bytes, os.PathLike or integer, not BufferedReader` – drewc Jun 09 '23 at 02:11
  • Alright, one other small fix: It appears that the `with open` clause was causing the type error, so changing that code to just this solved that problem: `uploaded_file = target_folder.files.create_upload_session(abs_file_path, size_chunk, print_upload_progress).execute_query()` Now I'm getting this error: `JSONDecodeError: Expecting value: line 1 column 1 (char 0)` (I don't know how to post a longer error here to show all of the trace back through the code.) Any thoughts? – drewc Jun 23 '23 at 18:15