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!
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Write a simple text file
await sandbox.files.write('/workspace/hello.txt', 'Hello, World!');
console.log('File written successfully');
// Read it back
const content = await sandbox.files.read('/workspace/hello.txt');
console.log(`Content: ${content}`);
await 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:import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Write multi-line content
const content = `Line 1
Line 2
Line 3
`;
await sandbox.files.write('/workspace/multiline.txt', content);
// Verify
const readContent = await sandbox.files.read('/workspace/multiline.txt');
console.log(readContent);
await sandbox.kill();
Expected Output:
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
import { Sandbox } from '@hopx-ai/sdk';
import * as fs from 'fs';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Read binary data from local file
const imageData = fs.readFileSync('local_image.png');
// Write to sandbox
await sandbox.files.writeBytes('/workspace/image.png', imageData);
console.log('Binary file written');
// Verify
const readData = await sandbox.files.readBytes('/workspace/image.png');
console.log(`Read back: ${readData.length} bytes`);
await 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:import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Write a Python script
const script = `
def calculate_sum(numbers):
return sum(numbers)
result = calculate_sum([1, 2, 3, 4, 5])
print(f"Sum: {result}")
`;
await sandbox.files.write('/workspace/calculator.py', script);
// Execute the script
const result = await sandbox.runCode(
'exec(open("/workspace/calculator.py").read())',
{ language: 'python' }
);
console.log(result.stdout); // "Sum: 15"
await sandbox.kill();
Expected Output:
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
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Write executable script (permissions handled automatically)
const script = '#!/bin/bash\necho "Hello from bash!"';
await sandbox.files.write('/workspace/script.sh', script);
console.log('Script created');
// Write regular file
await sandbox.files.write('/workspace/data.txt', 'Some data');
console.log('Regular file created');
await sandbox.kill();
Expected Output: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}
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Write JSON config
const config = {
api_key: 'sk-123',
debug: true,
timeout: 30
};
const configJson = JSON.stringify(config, null, 2);
await sandbox.files.write('/workspace/config.json', configJson);
// Read and verify
const readConfig = JSON.parse(await sandbox.files.read('/workspace/config.json'));
console.log(`Config written: ${JSON.stringify(readConfig)}`);
await 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
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Write large content
const largeContent = 'x'.repeat(1000000); // 1MB of data
await sandbox.files.write('/workspace/large.txt', largeContent);
console.log('Large file written');
// Verify size
const files = await sandbox.files.list('/workspace');
const largeFile = files.find(f => f.name === 'large.txt');
if (largeFile) {
console.log(`File size: ${(largeFile.size / 1024).toFixed(2)} KB`);
}
await 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()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Create directory structure
await sandbox.files.mkdir('/workspace/project');
await sandbox.files.mkdir('/workspace/project/src');
await sandbox.files.mkdir('/workspace/project/data');
// Write code file
const code = `
def process_data(data):
return [x * 2 for x in data]
if __name__ == "__main__":
result = process_data([1, 2, 3])
print(result)
`;
await sandbox.files.write('/workspace/project/src/main.py', code);
// Write config file
const config = { batch_size: 32, epochs: 10 };
await sandbox.files.write('/workspace/project/config.json', JSON.stringify(config, null, 2));
// Write data file
const data = '1,2,3\n4,5,6\n7,8,9\n';
await sandbox.files.write('/workspace/project/data/input.csv', data);
// List all files
const files = await sandbox.files.list('/workspace/project');
console.log('Created files:');
for (const f of files) {
if (f.isFile) {
console.log(` 📄 ${f.path} (${(f.size / 1024).toFixed(2)} KB)`);
}
}
await sandbox.kill();
Best Practices
1. Use Appropriate Method
Use write() for text files and write_bytes() for binary files (images, PDFs, etc.).
2. Set Permissions Correctly
Set appropriate file permissions (e.g., ‘0755’ for executables, ‘0644’ for regular files).
3. Create Directories First
Use files.mkdir() to create directories before writing files in them.
4. Handle Large Files
For very large files, consider using Upload instead of writing directly. 5. Write to Allowed Paths
Only write to allowed paths like /workspace and /tmp. System directories may be restricted.
Next Steps