如何将从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
相关产品推荐
相关产品推荐

