Upload files from your local filesystem to sandboxes. This is useful for transferring data files, scripts, or any local files you want to use in your sandbox.
Overview
File uploading is ideal for:
- Transferring local data files to sandboxes
- Uploading scripts and code files
- Moving configuration files
- Transferring datasets or models
Upload supports both text and binary files. Large files may take longer to upload - set appropriate timeouts for large transfers.
Basic Upload
Upload a file from local to sandbox:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Upload a local file
sandbox.files.upload('./local_data.csv', '/workspace/data.csv')
print("File uploaded successfully")
# Verify upload
if sandbox.files.exists('/workspace/data.csv'):
content = sandbox.files.read('/workspace/data.csv')
print(f"Uploaded content: {content[:100]}...")
sandbox.kill()
Upload with Timeout
Set timeout for large file uploads:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Upload large file with extended timeout
sandbox.files.upload('./large_dataset.zip', '/workspace/dataset.zip', timeout=300)
print("Large file uploaded")
# Verify
files = sandbox.files.list('/workspace')
for f in files:
if f.name == 'dataset.zip':
print(f"Uploaded: {f.name} ({f.size_mb:.2f} MB)")
sandbox.kill()
Upload Multiple Files
Upload multiple files in a loop:
from hopx_ai import Sandbox
import os
sandbox = Sandbox.create(template="code-interpreter")
# List of files to upload
files_to_upload = [
('./config.json', '/workspace/config.json'),
('./data.csv', '/workspace/data.csv'),
('./script.py', '/workspace/script.py')
]
# Upload all files
for local_path, remote_path in files_to_upload:
if os.path.exists(local_path):
sandbox.files.upload(local_path, remote_path)
print(f"✅ Uploaded: {local_path} → {remote_path}")
else:
print(f"⚠️ File not found: {local_path}")
# Verify all uploads
files = sandbox.files.list('/workspace')
print(f"\nUploaded {len(files)} files")
sandbox.kill()
Upload Binary Files
Upload binary files (images, PDFs, etc.):
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Upload image file
sandbox.files.upload('./image.png', '/workspace/image.png', timeout=60)
print("Image uploaded")
# Upload PDF
sandbox.files.upload('./document.pdf', '/workspace/document.pdf', timeout=60)
print("PDF uploaded")
# Verify binary files
files = sandbox.files.list('/workspace')
for f in files:
if f.name.endswith(('.png', '.pdf')):
print(f"Binary file: {f.name} ({f.size_kb:.2f} KB)")
sandbox.kill()
Upload to Specific Directory
Upload files to specific directories:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Create directory structure
sandbox.files.mkdir('/workspace/project')
sandbox.files.mkdir('/workspace/project/data')
sandbox.files.mkdir('/workspace/project/src')
# Upload to specific directories
sandbox.files.upload('./dataset.csv', '/workspace/project/data/dataset.csv')
sandbox.files.upload('./main.py', '/workspace/project/src/main.py')
sandbox.files.upload('./config.json', '/workspace/project/config.json')
# Verify structure
print("Project structure:")
for path in ['/workspace/project', '/workspace/project/data', '/workspace/project/src']:
files = sandbox.files.list(path)
print(f"\n{path}:")
for f in files:
print(f" {f.name}")
sandbox.kill()
Error Handling
Handle upload errors:
from hopx_ai import Sandbox
from hopx_ai.errors import FileOperationError
import os
sandbox = Sandbox.create(template="code-interpreter")
local_file = './data.csv'
try:
# Check if local file exists
if not os.path.exists(local_file):
print(f"Local file not found: {local_file}")
else:
# Upload with error handling
sandbox.files.upload(local_file, '/workspace/data.csv', timeout=120)
print("Upload successful")
except FileOperationError as e:
print(f"Upload failed: {e}")
except Exception as e:
print(f"Error: {e}")
sandbox.kill()
Complete Example
Here’s a complete upload workflow:
from hopx_ai import Sandbox
import os
sandbox = Sandbox.create(template="code-interpreter")
# Create project structure
sandbox.files.mkdir('/workspace/ml-project')
sandbox.files.mkdir('/workspace/ml-project/data')
sandbox.files.mkdir('/workspace/ml-project/models')
# Upload project files
files_to_upload = {
'./train.py': '/workspace/ml-project/train.py',
'./data/train.csv': '/workspace/ml-project/data/train.csv',
'./data/test.csv': '/workspace/ml-project/data/test.csv',
'./config.yaml': '/workspace/ml-project/config.yaml'
}
print("📤 Uploading files...")
for local_path, remote_path in files_to_upload.items():
if os.path.exists(local_path):
try:
sandbox.files.upload(local_path, remote_path, timeout=120)
file_size = os.path.getsize(local_path) / 1024
print(f" ✅ {local_path} → {remote_path} ({file_size:.2f} KB)")
except Exception as e:
print(f" ❌ Failed to upload {local_path}: {e}")
else:
print(f" ⚠️ File not found: {local_path}")
# Verify uploads
print("\n📋 Verifying uploads...")
files = sandbox.files.list('/workspace/ml-project')
total_size = 0
for f in files:
if f.is_file:
total_size += f.size
print(f" 📄 {f.path} ({f.size_kb:.2f} KB)")
print(f"\n✅ Total uploaded: {total_size / 1024:.2f} KB")
sandbox.kill()
Best Practices
1. Check Local File Existence
Always verify local files exist before attempting upload to avoid errors.
2. Set Appropriate Timeouts
For large files, set extended timeouts (60+ seconds) to avoid connection timeouts.
3. Create Directories First
Use files.mkdir() to create target directories before uploading files.
4. Handle Errors Gracefully
Wrap uploads in try/catch blocks to handle network errors, file not found, etc.
5. Verify Uploads
After uploading, verify files exist and check their sizes to ensure successful transfer.
Next Steps