Skip to main content
The Files resource provides comprehensive file system operations for working with files and directories inside sandboxes.

Accessing Files Resource

from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")
files = sandbox.files  # Lazy-loaded resource

Reading Files

read()

Read text file contents.
content = sandbox.files.read('/workspace/data.txt')
print(content)
Method Signature:
def read(
    self,
    path: str,
    *,
    timeout: Optional[int] = None
) -> str
Parameters:
  • path (str): File path (e.g., '/workspace/data.txt')
  • timeout (int, optional): Request timeout in seconds
Returns: File contents as string Raises:
  • FileNotFoundError: If file doesn’t exist
  • FileOperationError: If read fails
Example:
# Read configuration file
config = sandbox.files.read('/workspace/config.json')

# Read Python script
script = sandbox.files.read('/workspace/main.py')

read_bytes()

Read binary file contents.
image_data = sandbox.files.read_bytes('/workspace/plot.png')
with open('local_plot.png', 'wb') as f:
    f.write(image_data)
Method Signature:
def read_bytes(
    self,
    path: str,
    *,
    timeout: Optional[int] = None
) -> bytes
Use Cases:
  • Images (PNG, JPG, etc.)
  • PDFs
  • Binary data files
  • Compressed archives
Example:
# Read image
img = sandbox.files.read_bytes('/workspace/chart.png')

# Read PDF
pdf = sandbox.files.read_bytes('/workspace/document.pdf')

Writing Files

write()

Write text file contents.
sandbox.files.write('/workspace/hello.py', 'print("Hello, World!")')
Method Signature:
def write(
    self,
    path: str,
    content: str,
    mode: str = "0644",
    *,
    timeout: Optional[int] = None
) -> None
Parameters:
  • path (str): File path
  • content (str): File contents to write
  • mode (str): File permissions (default: "0644")
  • timeout (int, optional): Request timeout
Example:
# Write Python script
sandbox.files.write(
    '/workspace/script.py',
    '''
def hello():
    print("Hello, World!")

hello()
'''
)

# Write with executable permissions
sandbox.files.write(
    '/workspace/script.sh',
    '#!/bin/bash\necho "Hello"',
    mode='0755'
)

write_bytes()

Write binary file contents.
with open('image.png', 'rb') as f:
    image_data = f.read()
sandbox.files.write_bytes('/workspace/image.png', image_data)
Method Signature:
def write_bytes(
    self,
    path: str,
    content: bytes,
    mode: str = "0644",
    *,
    timeout: Optional[int] = None
) -> None
Example:
# Write image
with open('chart.png', 'rb') as f:
    sandbox.files.write_bytes('/workspace/chart.png', f.read())

# Write binary data
data = b'\x00\x01\x02\x03'
sandbox.files.write_bytes('/workspace/data.bin', data)

Directory Operations

list()

List directory contents.
files = sandbox.files.list('/workspace')
for f in files:
    if f.is_file:
        print(f"📄 {f.name}: {f.size_kb:.2f} KB")
    else:
        print(f"📁 {f.name}/")
Method Signature:
def list(
    self,
    path: str = "/workspace",
    *,
    timeout: Optional[int] = None
) -> List[FileInfo]
Returns: List of FileInfo objects FileInfo Properties:
  • name (str): File/directory name
  • path (str): Full path
  • size (int): Size in bytes
  • size_kb (float): Size in KB (convenience property)
  • is_file (bool): True if file, False if directory
  • is_directory (bool): True if directory
  • permissions (str): File permissions
  • modified_time (str): Last modified time
Example:
# List workspace
files = sandbox.files.list('/workspace')
for f in files:
    print(f"{f.name} ({f.size_kb:.2f} KB)")

# List specific directory
project_files = sandbox.files.list('/workspace/project')

mkdir()

Create directory.
sandbox.files.mkdir('/workspace/data')
sandbox.files.mkdir('/workspace/project/src')  # Creates nested directories
Method Signature:
def mkdir(
    self,
    path: str,
    *,
    timeout: Optional[int] = None
) -> None
Example:
# Create single directory
sandbox.files.mkdir('/workspace/data')

# Create nested directories
sandbox.files.mkdir('/workspace/project/src/utils')

exists()

Check if file or directory exists.
if sandbox.files.exists('/workspace/data.csv'):
    print("File exists!")
    content = sandbox.files.read('/workspace/data.csv')
else:
    print("File not found")
Method Signature:
def exists(
    self,
    path: str,
    *,
    timeout: Optional[int] = None
) -> bool
Returns: True if exists, False otherwise Example:
# Check file existence
if sandbox.files.exists('/workspace/config.json'):
    config = sandbox.files.read('/workspace/config.json')

# Check directory existence
if sandbox.files.exists('/workspace/data'):
    files = sandbox.files.list('/workspace/data')

remove()

Delete file or directory.
# Remove file
sandbox.files.remove('/workspace/temp.txt')

# Remove directory (recursive)
sandbox.files.remove('/workspace/old_data')
Method Signature:
def remove(
    self,
    path: str,
    *,
    timeout: Optional[int] = None
) -> None
Raises:
  • FileNotFoundError: If file doesn’t exist
  • FileOperationError: If delete fails
Example:
# Remove single file
sandbox.files.remove('/workspace/temp.txt')

# Remove directory and all contents
sandbox.files.remove('/workspace/cache')

File Transfer

upload()

Upload file from local filesystem to sandbox.
sandbox.files.upload('./data.csv', '/workspace/data.csv')
Method Signature:
def upload(
    self,
    local_path: str,
    remote_path: str,
    *,
    timeout: Optional[int] = None
) -> None
Parameters:
  • local_path (str): Path to local file
  • remote_path (str): Destination path in sandbox
  • timeout (int, optional): Request timeout (recommended: 60+ for large files)
Raises:
  • FileNotFoundError: If local file doesn’t exist
  • FileOperationError: If upload fails
Example:
# Upload small file
sandbox.files.upload('./config.json', '/workspace/config.json')

# Upload large file with extended timeout
sandbox.files.upload(
    './large_dataset.zip',
    '/workspace/dataset.zip',
    timeout=300  # 5 minutes
)

download()

Download file from sandbox to local filesystem.
sandbox.files.download('/workspace/result.csv', './result.csv')
Method Signature:
def download(
    self,
    remote_path: str,
    local_path: str,
    *,
    timeout: Optional[int] = None
) -> None
Parameters:
  • remote_path (str): Path in sandbox
  • local_path (str): Destination path on local filesystem
  • timeout (int, optional): Request timeout (recommended: 60+ for large files)
Raises:
  • FileNotFoundError: If file doesn’t exist in sandbox
  • FileOperationError: If download fails
Example:
# Download text file
sandbox.files.download('/workspace/output.txt', './output.txt')

# Download image
sandbox.files.download('/workspace/plot.png', './plot.png')

# Download large file
sandbox.files.download(
    '/workspace/large_result.zip',
    './result.zip',
    timeout=300
)

File Watching (WebSocket)

watch()

Watch filesystem for changes via WebSocket (async).
import asyncio

async def watch_files():
    sandbox = Sandbox.create(template="code-interpreter")
    
    async for event in sandbox.files.watch("/workspace"):
        print(f"{event['event']}: {event['path']}")
        
        if event['type'] == 'change':
            if event['event'] == 'created':
                print(f"File created: {event['path']}")
            elif event['event'] == 'modified':
                print(f"File modified: {event['path']}")
            elif event['event'] == 'deleted':
                print(f"File deleted: {event['path']}")

asyncio.run(watch_files())
Method Signature:
async def watch(
    self,
    path: str = "/workspace",
    *,
    timeout: Optional[int] = None
) -> AsyncIterator[Dict[str, Any]]
Event Types:
  • "created": File/directory created
  • "modified": File modified
  • "deleted": File/directory deleted
  • "renamed": File/directory renamed
Example:
import asyncio

async def monitor_changes():
    sandbox = Sandbox.create(template="code-interpreter")
    
    # Start watching
    async for event in sandbox.files.watch("/workspace"):
        if event['type'] == 'change':
            print(f"{event['event']}: {event['path']}")
            
            # Stop after 10 events
            if event_count >= 10:
                break

asyncio.run(monitor_changes())

Error Handling

Handle file operation errors:
from hopx_ai.errors import FileNotFoundError, FileOperationError

try:
    content = sandbox.files.read('/workspace/missing.txt')
except FileNotFoundError as e:
    print(f"File not found: {e.path}")
except FileOperationError as e:
    print(f"File operation failed: {e.message}")
    print(f"Operation: {e.operation}")

Best Practices

1. Check File Existence

if sandbox.files.exists('/workspace/data.csv'):
    content = sandbox.files.read('/workspace/data.csv')
else:
    print("File not found, creating...")
    sandbox.files.write('/workspace/data.csv', 'default,data')

2. Use Appropriate Timeouts

# Small files
content = sandbox.files.read('/workspace/config.json', timeout=10)

# Large files
sandbox.files.upload('./large.zip', '/workspace/large.zip', timeout=300)

3. Handle Binary Files Correctly

# Text files
content = sandbox.files.read('/workspace/data.txt')

# Binary files
image_data = sandbox.files.read_bytes('/workspace/image.png')

4. Create Directories Before Writing

# Create directory structure
sandbox.files.mkdir('/workspace/project/data')

# Then write files
sandbox.files.write('/workspace/project/data/config.json', '{}')

5. Use FileInfo for Metadata

files = sandbox.files.list('/workspace')
for f in files:
    if f.is_file and f.size_kb > 100:
        print(f"Large file: {f.name} ({f.size_kb:.2f} KB)")

Examples

Working with CSV Files

# Write CSV
csv_data = "name,age\nAlice,30\nBob,25"
sandbox.files.write('/workspace/data.csv', csv_data)

# Read CSV
content = sandbox.files.read('/workspace/data.csv')

# Process with pandas
result = sandbox.run_code(
    '''
import pandas as pd
df = pd.read_csv('/workspace/data.csv')
print(df.describe())
'''
)

# Download result
sandbox.files.download('/workspace/result.csv', './result.csv')

Working with Images

# Upload image
sandbox.files.upload('./input.png', '/workspace/input.png')

# Process image
result = sandbox.run_code(
    '''
from PIL import Image
img = Image.open('/workspace/input.png')
img = img.resize((800, 600))
img.save('/workspace/output.png')
''',
    rich=True
)

# Download processed image
sandbox.files.download('/workspace/output.png', './output.png')

Directory Management

# Create project structure
sandbox.files.mkdir('/workspace/project')
sandbox.files.mkdir('/workspace/project/src')
sandbox.files.mkdir('/workspace/project/tests')

# Write files
sandbox.files.write('/workspace/project/src/main.py', 'print("Hello")')
sandbox.files.write('/workspace/project/tests/test_main.py', 'def test(): pass')

# List structure
files = sandbox.files.list('/workspace/project')
for f in files:
    print(f"{'📁' if f.is_directory else '📄'} {f.path}")