Hello @vgrem , the following code raises ValueError
.
...
web = client_context.web
client_context.load(web)
server_relative_url = f'/{folder_name}/{filename}'
logger.info(f'relative path: {server_relative_url}')
file = web.get_file_by_server_relative_url(server_relative_url)
return file.read()
It would be fine to add some message to that error like this
```
raise ValueError('you did this and that wrong...')
adding this before file.read()
fixed my issue
client_context.load(file)
client_context.execute_query()
That's right, those were the missing methods, File.read
method expects file metadata ( ServerRelativeUrl
property in particular to to properly address the file) to be retrieved before the file gets downloaded:
client_context.load(file)
client_context.execute_query()
Since it might not be that most intuitive to download a file content, another method File.download
has been introduced, now file could be downloaded like this:
with open(download_path, "wb") as local_file:
source_file = ctx.web.get_file_by_server_relative_url(file_url)
source_file.download(local_file)
ctx.execute_query()
Thanks @vgrem, this is a great usability improvement for newcomers!
file.download is it part of 2.1.7.post1?
latest from pip can only go that far
pip list | grep -i office
Office365-REST-Python-Client 2.1.7.post1
2.1.8
pip install --upgrade Office365-REST-Python-Client==2.1.8
ERROR: Could not find a version that satisfies the requirement Office365-REST-Python-Client==2.1.8 (from versions: 1.0.0, 1.0.1, 1.1.0, 2.0.0, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.6.post2, 2.1.7.post1)
ERROR: No matching distribution found for Office365-REST-Python-Client==2.1.8
==== Temp Workaround ====
import tempfile
import os
download_path = os.path.join(tempfile.mkdtemp(), os.path.basename(location))
file_url = '/sites/Integration/Shared Documents/SomeFolder/somefile.csv'
download_path = os.path.join(tempfile.mkdtemp(), os.path.basename(file_url))
download_path
with open(download_path, "wb") as local_file:
source_file = ctx.web.get_file_by_server_relative_url(file_url)
source_file
ctx.load(source_file)
ctx.execute_query()
r = source_file.read()
ctx.execute_query()
print("Data:", r)
local_file.write(r)
local_file.close()
print("[Ok] file has been downloaded: {0}".format(download_path))