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

如何将从SharePoint下载zip文件的PowerShell命令转为可用Python代码

问题根因
  • URL路径错误:PowerShell中`$value的反引号是PowerShell自身的转义字符,作用是阻止PowerShell将$value解析为本地变量,实际发送到SharePoint服务端的URL路径后缀是$value,不存在反引号。你在Python代码中将反引号也写入了URL,导致服务端无法识别请求路径,返回400错误。
  • 缺失必要请求头(可选优化):SharePoint REST API要求部分场景下携带Accept头,否则可能返回异常响应。
修正后的代码
import requests

FileUrl = "https://xxx.sharepoint.com/sites/xxx/_api/Web/GetFileByServerRelativePath(decodedurl='sites/xxx/path/to/file.zip')/$value"
headers = {
    "Authorization": "Bearer eyJ...",
    "Accept": "application/json;odata=verbose"
}
# 请求错误时直接抛出异常,避免后续写入无效内容
r = requests.get(FileUrl, headers=headers)
r.raise_for_status()

with open(r"C:\path\to\file.zip", "wb") as f:
    f.write(r.content)

如果需要下载较大的zip文件,可改用流式下载减少内存占用:

import requests

FileUrl = "https://xxx.sharepoint.com/sites/xxx/_api/Web/GetFileByServerRelativePath(decodedurl='sites/xxx/path/to/file.zip')/$value"
headers = {
    "Authorization": "Bearer eyJ...",
    "Accept": "application/json;odata=verbose"
}

with requests.get(FileUrl, headers=headers, stream=True) as r:
    r.raise_for_status()
    with open(r"C:\path\to\file.zip", "wb") as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:36:03