如何用Python下载SharePoint文件夹文件?API返回空JSON求助
Hey there! Let's break down why your API call is returning an empty file list even though you can see files in the web interface. I'll walk you through common fixes and adjusted code since you're new to Python and SharePoint REST APIs.
Common Issues & Fixes
1. Incorrect Server Relative URL Format
SharePoint's GetFolderByServerRelativeUrl endpoint is picky about path formatting:
- No trailing slashes: Your original path ends with
/– remove that, as the API won't recognize the folder correctly. - Verify the full relative path: Double-check that your path starts with the site name (e.g.,
/some-site/...). The path from the SharePoint details pane should be correct, but ensure there are no typos.
2. Misconfigured sharepy Session
The sharepy.connect method needs your full site URL (not just the root domain) to properly associate permissions and API calls with your site. Using only company.sharepoint.com can lead to ambiguous API routing.
3. Missing Debug Steps
Before fetching files, confirm you're actually targeting the right folder. Checking the folder's basic metadata (like item count) will tell you if the API is finding your folder at all.
Adjusted Code with Debugging
Here's a revised version of your code with fixes and debugging checks:
import sharepy import os # 1. Connect to your specific SharePoint site (full URL, not just root domain) sess = sharepy.connect( site='https://company.sharepoint.com/some-site', username='username', password='password' ) # 2. Server relative path: no trailing slash, starts with your site name server_relative_folder = '/some-site/Documents/Folder1/Folder2/Folder3' # 3. First, verify we're targeting the correct folder folder_info_response = sess.get( f"https://company.sharepoint.com/_api/web/GetFolderByServerRelativeUrl('{server_relative_folder}')" ) folder_data = folder_info_response.json()['d'] print(f"Folder Name: {folder_data['Name']}") print(f"Total Items (files + subfolders): {folder_data['ItemCount']}") # 4. Fetch files only if the folder has items if folder_data['ItemCount'] > 0: files_response = sess.get( f"https://company.sharepoint.com/_api/web/GetFolderByServerRelativeUrl('{server_relative_folder}')/Files" ) files_list = files_response.json()['d']['results'] if files_list: print(f"\nFound {len(files_list)} files:") for file in files_list: print(f"- {file['Name']}") else: print("\nNo files found in this folder – check if items are in subfolders instead!") else: print("\nFolder not found or contains no items. Double-check your server relative path.")
Next Steps: Download & Upload Files
Once you can successfully fetch the file list, here's how to download them to your local machine and upload a merged file back to SharePoint:
Download Files
# Create a local folder to store downloads local_download_dir = './sharepoint_downloads' os.makedirs(local_download_dir, exist_ok=True) for file in files_list: # Build full URL to the file file_url = f"https://company.sharepoint.com{file['ServerRelativeUrl']}" local_file_path = os.path.join(local_download_dir, file['Name']) # Download the file sess.getfile(file_url, local_file_path) print(f"Downloaded: {local_file_path}")
Upload Merged File
# Path to your merged file (after conversion) merged_file_path = './merged_output.csv' # Adjust extension based on your file type target_folder_path = '/some-site/Documents/ProcessedFiles' # Target SharePoint folder # Upload the file (overwrite if it exists) with open(merged_file_path, 'rb') as file_content: upload_response = sess.post( url=f"https://company.sharepoint.com/_api/web/GetFolderByServerRelativeUrl('{target_folder_path}')/Files/add(url='{os.path.basename(merged_file_path)}', overwrite=true)", data=file_content, headers={'Content-Type': 'text/csv'} # Update this to match your file type (e.g., application/pdf) ) if upload_response.status_code == 200: print("\nMerged file uploaded successfully!") else: print(f"\nUpload failed with status code: {upload_response.status_code}")
Key Notes
- If
ItemCountis greater than 0 butFilesis empty, your folder likely contains subfolders instead of files. Use the/Foldersendpoint instead of/Filesto list them. - Always match the
Content-Typeheader in the upload request to your file's actual type (e.g.,application/vnd.openxmlformats-officedocument.spreadsheetml.sheetfor Excel files).
内容的提问来源于stack exchange,提问作者Rituraj Achuthan

