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

使用Python上传CSV至SharePoint时遇401(ID3035)错误求助

解决SharePoint文件上传401 ID3035错误的方案

你的问题出在手动拼接REST上传URL时的格式问题,且混合使用office365库和原生requests调用容易引发认证或路径错误。直接使用office365库提供的文件上传API可避免这类问题,以下是修正后的实现:

核心修正点

  • 移除手动拼接REST上传URL的逻辑,改用office365库内置的upload_file方法
  • 确保目标子文件夹存在(不存在则自动创建)
  • 简化认证后的文件上传流程,减少手动构造请求的出错概率

修正后的完整代码

from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
import msal
import os

sharepoint_site_url = "https://companyname.sharepoint.com/sites/PowerBILookUp"
document_library_name = "Shared Documents"
subfolder_name = "SubFolder"

# Azure AD App Registration details
client_id = "client_id"
client_secret = "client_secret"
tenant_id = "tenant_id"

# Path to the CSV file you want to upload
local_csv_path = "C:\\Users\\Administrator\\Downloads\\orders.csv"
destination_file_name = "orders2.csv"

# Authentication authority URL
authority_url = f"https://login.microsoftonline.com/{tenant_id}"
app = msal.ConfidentialClientApplication(
    client_id,
    authority=authority_url,
    client_credential=client_secret,
)

# Acquire a token for SharePoint
token_response = app.acquire_token_for_client(scopes=["https://companyname.sharepoint.com/.default"])
if "access_token" in token_response:
    access_token = token_response["access_token"]
    print(f"Access token acquired: {access_token[:30]}...")

    try:
        # Create SharePoint client context
        ctx = ClientContext(sharepoint_site_url).with_access_token(access_token)
        
        # Get root document library folder (full server relative path)
        doc_lib_folder = ctx.web.get_folder_by_server_relative_url(f"/sites/PowerBILookUp/{document_library_name}")
        ctx.execute_query()
        print(f"Accessed document library: {document_library_name}")

        # Ensure target subfolder exists (create if not present)
        target_folder = doc_lib_folder.folders.add(subfolder_name)
        ctx.execute_query()
        print(f"Target subfolder ready: {subfolder_name}")

        # Upload file to the target subfolder
        with open(local_csv_path, 'rb') as file_content:
            target_file = target_folder.upload_file(destination_file_name, file_content).execute_query()
        
        print(f"File uploaded successfully: {target_file.serverRelativeUrl}")

    except Exception as e:
        print(f"Operation failed: {e}")
else:
    print(f"Token acquisition failed: {token_response.get('error_description')}")

额外说明

  1. 服务器相对路径:SharePoint的服务器相对路径需包含站点前缀(/sites/PowerBILookUp/),此前仅用Shared Documents能访问是因为office365库做了隐式处理,但手动拼接URL时易遗漏前缀导致路径错误。
  2. 子文件夹处理:代码添加了自动创建子文件夹的逻辑,若目标子文件夹已存在,folders.add方法不会报错,仅返回已存在的文件夹对象。
  3. 权限验证:确保Azure AD应用注册已被授予SharePoint站点的文件读写权限(在Azure门户的API权限中添加Sites.Manage.All或Sites.ReadWrite.All权限并完成管理员同意)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 17:22:14