You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过SharePoint REST API下载文件时出现空文件问题求助

使用Office365-REST-Python-Client下载SharePoint文件生成空文件的解决方案

你遇到的空文件/损坏文件问题,核心原因是代码仅获取了文件的元数据对象,没有实际读取并写入文件内容到本地。原代码里的ctx.web.get_file_by_server_relative_url(...).execute_query()只是完成了文件对象的加载,并没有触发内容下载操作。

修复方式1:使用download()方法直接写入文件

Office365-REST-Python-Client提供了download()方法,可以直接将文件内容写入本地文件句柄,简化操作:

download_path = os.path.join(tempfile.mkdtemp(), os.path.basename('/sites/###/Shared Documents/TestFile.csv'))
with open(download_path, "wb") as local_file:
    # 调用download方法将文件内容写入本地文件
    ctx.web.get_file_by_server_relative_url('/sites/###/Shared Documents/TestFile.csv').download(local_file).execute_query()
print("[Ok] file has been downloaded into: {0}".format(download_path))

修复方式2:手动读取二进制内容写入文件

如果需要更灵活的处理(比如先处理内容再保存),可以使用open_binary()方法获取文件二进制流,再写入本地:

download_path = os.path.join(tempfile.mkdtemp(), os.path.basename('/sites/###/Shared Documents/TestFile.csv'))
file_obj = ctx.web.get_file_by_server_relative_url('/sites/###/Shared Documents/TestFile.csv')
# 获取文件二进制内容
file_content = file_obj.open_binary().execute_query()
with open(download_path, "wb") as local_file:
    local_file.write(file_content)
print("[Ok] file has been downloaded into: {0}".format(download_path))

额外验证与优化建议

  • 下载完成后检查本地文件大小,和SharePoint上的文件大小对比,确认内容已正确写入
  • 确保server_relative_url的路径完全正确(可从SharePoint文件属性中复制官方路径)
  • 如果需要批量下载文件,可循环遍历files集合直接处理:
for myfile in files:
    print(f"正在下载: {myfile.properties['Name']}")
    download_path = os.path.join(tempfile.mkdtemp(), myfile.properties['Name'])
    with open(download_path, "wb") as local_file:
        myfile.download(local_file).execute_query()
    print(f"已保存到: {download_path}")

内容的提问来源于stack exchange,提问作者misterducky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:33:13