Office365-REST-Python-Client icon indicating copy to clipboard operation
Office365-REST-Python-Client copied to clipboard

Reading a JSON file from OneDrive

Open Albarion opened this issue 3 years ago • 4 comments

I'm using the "OneDrive file download" example to download a JSON file. This results in : TypeError: a bytes-like object is required, not 'str'

If I write to a io.StringIO object the response is just the value of the last JSON key. Is this a bug or am I missing something ?

Albarion avatar Nov 16 '22 15:11 Albarion

We have got the same issue when trying to download a json file. Current (dirty) solution is to rename it to something like myfile.jsn ^^ With the changed file ending it is working fine.

path = ... # to download
drive = ... # drive of your sharepoint

item = drive.root.get_by_path(path).get().execute_query()
if item is None:
    raise Exception(f"Unknown file {path}")

base_name = os.path.basename(item.web_url)
file_path = os.path.join(tempfile.gettempdir(), base_name)
if path.lower().endswith(".json"):
    item.copy(base_name + ".jsn", item.parent_reference).execute_query()
    copied = drive.root.get_by_path(path + ".jsn").get().execute_query()
    with open(file_path, "w") as downloaded_file:
        content = copied.get_content().execute_query().value.decode("utf-8")
        downloaded_file.write(content)
    copied.delete_object().execute_query()
else:
    with open(file_path, "wb") as downloaded_file:
        item.download(downloaded_file).execute_query()

with open(file_path) as myFile:
  # do something

cpraschl avatar May 10 '23 08:05 cpraschl