Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt

Use this file to discover all available pages before exploring further.

Write files to your sandbox filesystem. HopX supports both text and binary file writing with automatic encoding and permission handling.

Overview

File writing is essential for:
  • Creating scripts and code files
  • Saving generated data and results
  • Writing configuration files
  • Storing outputs from computations
Files can be written to allowed paths like /workspace and /tmp. Writing to system directories may be restricted for security.

Writing Text Files

Write text files as strings:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Write a simple text file
sandbox.files.write('/workspace/hello.txt', 'Hello, World!')
print("File written successfully")

# Read it back
content = sandbox.files.read('/workspace/hello.txt')
print(f"Content: {content}")

sandbox.kill()
Expected Output:
File written successfully
Content: Hello, World!

Writing Multi-line Files

Write files with multiple lines:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Write multi-line content
content = '''Line 1
Line 2
Line 3
'''
sandbox.files.write('/workspace/multiline.txt', content)

# Verify
read_content = sandbox.files.read('/workspace/multiline.txt')
print(read_content)

sandbox.kill()
Expected Output:
Line 1
Line 2
Line 3

Writing Binary Files

Write binary files (images, PDFs, etc.):
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Read binary data from local file
with open('local_image.png', 'rb') as f:
    image_data = f.read()

# Write to sandbox
sandbox.files.write_bytes('/workspace/image.png', image_data)
print("Binary file written")

# Verify
read_data = sandbox.files.read_bytes('/workspace/image.png')
print(f"Read back: {len(read_data)} bytes")

sandbox.kill()
Expected Output:
Binary file written
Read back: 245760 bytes

Writing Code Files

Write and execute code files:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Write a Python script
script = '''
def calculate_sum(numbers):
    return sum(numbers)

result = calculate_sum([1, 2, 3, 4, 5])
print(f"Sum: {result}")
'''

sandbox.files.write('/workspace/calculator.py', script)

# Execute the script
result = sandbox.run_code(
    'exec(open("/workspace/calculator.py").read())',
    language='python'
)
print(result.stdout)  # "Sum: 15"

sandbox.kill()
Expected Output:
Sum: 15

File Permissions

Set file permissions when writing:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

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

# Write regular file with default permissions
sandbox.files.write('/workspace/data.txt', 'Some data', mode='0644')
print("Regular file created")

sandbox.kill()
Expected Output:
Executable script created
Regular file created

Writing Configuration Files

Write JSON, YAML, or other configuration files:
from hopx_ai import Sandbox
import json

sandbox = Sandbox.create(template="code-interpreter")

# Write JSON config
config = {
    "api_key": "sk-123",
    "debug": True,
    "timeout": 30
}
config_json = json.dumps(config, indent=2)
sandbox.files.write('/workspace/config.json', config_json)

# Read and verify
read_config = json.loads(sandbox.files.read('/workspace/config.json'))
print(f"Config written: {read_config}")

sandbox.kill()
Expected Output:
Config written: {'api_key': 'sk-123', 'debug': True, 'timeout': 30}

Writing Large Files

For large files, consider chunking or using upload:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Write large content
large_content = "x" * 1000000  # 1MB of data
sandbox.files.write('/workspace/large.txt', large_content, timeout=120)
print("Large file written")

# Verify size
files = sandbox.files.list('/workspace')
for f in files:
    if f.name == 'large.txt':
        print(f"File size: {f.size_kb:.2f} KB")

sandbox.kill()
Expected Output:
Large file written
File size: 976.56 KB

Complete Example

Here’s a complete example showing file writing workflow:
from hopx_ai import Sandbox
import json

sandbox = Sandbox.create(template="code-interpreter")

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

# Write code file
code = '''
def process_data(data):
    return [x * 2 for x in data]

if __name__ == "__main__":
    result = process_data([1, 2, 3])
    print(result)
'''
sandbox.files.write('/workspace/project/src/main.py', code)

# Write config file
config = {"batch_size": 32, "epochs": 10}
sandbox.files.write('/workspace/project/config.json', json.dumps(config, indent=2))

# Write data file
data = "1,2,3\n4,5,6\n7,8,9\n"
sandbox.files.write('/workspace/project/data/input.csv', data)

# List all files
files = sandbox.files.list('/workspace/project')
print("Created files:")
for f in files:
    if f.is_file:
        print(f"  📄 {f.path} ({f.size_kb:.2f} KB)")

sandbox.kill()

Best Practices

1

1. Use Appropriate Method

Use write() for text files and write_bytes() for binary files (images, PDFs, etc.).
2

2. Set Permissions Correctly

Set appropriate file permissions (e.g., ‘0755’ for executables, ‘0644’ for regular files).
3

3. Create Directories First

Use files.mkdir() to create directories before writing files in them.
4

4. Handle Large Files

For very large files, consider using Upload instead of writing directly.
5

5. Write to Allowed Paths

Only write to allowed paths like /workspace and /tmp. System directories may be restricted.

Next Steps