Office365-rest-python-client: 无法通过 get_file_by_server_relative_url 下载文件

创建于 2020-05-21  ·  4评论  ·  资料来源: vgrem/Office365-REST-Python-Client

你好@vgrem ,以下代码引发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()

可以像这样向该错误添加一些消息
``
raise ValueError('你做错了那个...')

question

所有4条评论

file.read()解决我的问题之前添加这个

client_context.load(file)
client_context.execute_query()

没错,那些是缺少的方法, File.read方法期望在文件下载之前检索文件元数据(特别是ServerRelativeUrl属性以正确寻址文件):

client_context.load(file)  
client_context.execute_query()

由于下载文件内容可能不是最直观,因此引入了另一种方法File.download ,现在可以像这样下载文件:

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()

谢谢@vgrem ,这对新手来说是一个很好的可用性改进!

file.download 是 2.1.7.post1 的一部分吗?

来自 pip 的最新信息只能走那么远
点子列表| grep -i 办公室
Office365-REST-Python-Client 2.1.7.post1

2.1.8
pip install --upgrade Office365-REST-Python-Client==2.1.8
错误:找不到满足要求的版本 Office365-REST-Python-Client==2.1.8(来自版本: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)
错误:找不到 Office365-REST-Python-Client==2.1.8 的匹配分发

==== 临时解决方法 ====

导入临时文件
导入操作系统
下载路径 = os.path.join(tempfile.mkdtemp(), os.path.basename(location))
file_url = '/sites/Integration/Shared Documents/SomeFolder/somefile.csv'
下载路径 = os.path.join(tempfile.mkdtemp(), os.path.basename(file_url))
下载路径
使用 open(download_path, "wb") 作为 local_file:
source_file = ctx.web.get_file_by_server_relative_url(file_url)
源文件
ctx.load(source_file)
ctx.execute_query()
r = source_file.read()
ctx.execute_query()
打印(“数据:”,r)
local_file.write(r)
local_file.close()
print("[Ok] 文件已下载:{0}".format(download_path))

此页面是否有帮助?
0 / 5 - 0 等级