如何使用urllib2将桌面文件上传至Jupyter Notebook?
Uploading a Desktop File to Jupyter Notebook with
urllib2 Got it, let's walk through how to upload your desktop file to Jupyter Notebook using urllib2 step by step. Since urllib2 is a Python 2.x library, I’ll tailor the code and explanations to that environment.
First, a quick overview: Jupyter exposes a REST API we can use to upload files, and we need to construct a multipart/form-data request (the standard for file uploads) with urllib2 since it doesn’t have built-in support for this content type.
Prerequisites
- Know your Jupyter Notebook’s base URL (usually
http://localhost:8888by default) - Grab your Jupyter authentication token: You’ll find this in the terminal output when you start Jupyter, or in the URL bar of your Jupyter browser tab (looks like
?token=abc123...) - Have the full file path to your desktop file ready (e.g.,
/Users/YourName/Desktop/report.csvfor macOS/Linux,r'C:\Users\YourName\Desktop\report.csv'for Windows)
Full Code Example
Here’s a complete, working script you can adapt:
import urllib2 import uuid import os import mimetypes # -------------------------- # Replace these values! # -------------------------- jupyter_base_url = 'http://localhost:8888' jupyter_token = 'your_jupyter_token_here' desktop_file_path = '/Users/YourName/Desktop/your_file.txt' # macOS/Linux # desktop_file_path = r'C:\Users\YourName\Desktop\your_file.txt' # Uncomment for Windows target_jupyter_dir = '' # Empty string = Jupyter's root directory; use 'subfolder' for a subdir # Generate a unique boundary for multipart request boundary = uuid.uuid4().hex content_type = 'multipart/form-data; boundary={}'.format(boundary) # Get file details file_name = os.path.basename(desktop_file_path) # Guess MIME type, fall back to binary if unknown mime_type, _ = mimetypes.guess_type(desktop_file_path) mime_type = mime_type or 'application/octet-stream' # Read file content with open(desktop_file_path, 'rb') as f: file_content = f.read() # Build the multipart request body body_parts = [] # Add file part body_parts.append('--{}'.format(boundary)) body_parts.append('Content-Disposition: form-data; name="file"; filename="{}"'.format(file_name)) body_parts.append('Content-Type: {}'.format(mime_type)) body_parts.append('') body_parts.append(file_content) # Add target directory part (required by Jupyter API) body_parts.append('--{}'.format(boundary)) body_parts.append('Content-Disposition: form-data; name="path"') body_parts.append('') body_parts.append(target_jupyter_dir) # Close the boundary body_parts.append('--{}--'.format(boundary)) body_parts.append('') # Combine parts into a single request body (Python 2.x handles str/bytes seamlessly here) request_body = '\r\n'.join(body_parts) # Construct the upload URL with authentication token upload_url = '{}?token={}'.format(jupyter_base_url + '/api/files', jupyter_token) # Create and send the request req = urllib2.Request(upload_url, data=request_body) req.add_header('Content-Type', content_type) req.add_header('Content-Length', str(len(request_body))) try: response = urllib2.urlopen(req) print('✅ Upload successful! Status code:', response.getcode()) print('Response:', response.read()) except urllib2.HTTPError as e: print('❌ Upload failed with HTTP error:', e.code) print('Error details:', e.read()) except urllib2.URLError as e: print('❌ Connection error:', e.reason)
Key Notes
- Token Authentication: Jupyter requires a token to prevent unauthorized access, so don’t skip adding it to the URL.
- Windows File Paths: Use a raw string (
r'C:\...') or double backslashes (C:\\...) to avoid escape character issues. - Target Directory: If you want to upload to a subfolder in Jupyter, set
target_jupyter_dirto the folder name (e.g.,'data'). - Python 2.x Warning: Keep in mind Python 2 is no longer supported. If you can switch to Python 3, using the
requestslibrary would simplify this process drastically, but since you specifiedurllib2, the above code should work.
内容的提问来源于stack exchange,提问作者V. Andy
相关产品推荐
相关产品推荐

