I'm having an issue with trying to pull some files out of SharePoint Online using Python, thought I don't think this is an issue with my code (but maybe it is) but more an issue with permissions accessing the file in question.
I am using vgrem's Office365-REST-Python-Client library, with some code from the examples folder and from a very helpful answer on another Stack Overflow post.
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
import os
import tempfile
sp_site = 'https://###.sharepoint.com/sites/###/'
relative_url = "/sites/###/Shared Documents"
client_credentials = UserCredential('###', '###')
ctx = ClientContext(sp_site).with_credentials(client_credentials)
libraryRoot = ctx.web.get_folder_by_server_relative_path(relative_url)
ctx.load(libraryRoot)
ctx.execute_query()
files = libraryRoot.files
folders = libraryRoot.folders
ctx.load(files)
ctx.execute_query()
for myfile in files:
print("Folder name: {0}".format(myfile.properties))
download_path = os.path.join(tempfile.mkdtemp(), os.path.basename('/sites/###/Shared Documents/TestFile.csv'))
with open(download_path, "wb") as local_file:
file = ctx.web.get_file_by_server_relative_url('/sites/###/Shared Documents/TestFile.csv').execute_query()
print("[Ok] file has been downloaded into: {0}".format(download_path))
The main issue I'm having is that I'm able to see all of the files in the directory I want (running this script returns the property dictionary for all four files in the folder), but when it tries to download the file, it's just saving an empty file.
For CSVs, this just opens blank, and for .xlsx files, it says it's corrupted.
The log-in credentials I'm using should have no problem downloading the file in question, and when I just take the fully constructed URL to the file and paste it in a browser, it downloads it no problem. I'm not sure what's causing the issue. I've confirmed we're using SharePoint Online and not any on-premises solution. I'm stumped.