Read files from your sandbox filesystem. HopX supports both text and binary file reading with automatic encoding handling.
Overview
File reading is essential for:
- Accessing generated outputs from code execution
- Reading configuration files
- Processing data files
- Retrieving logs and results
Files can be read from allowed paths like /workspace and /tmp. Reading from system directories may be restricted for security.
Reading Text Files
Read text files as strings:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Write a file first
sandbox.files.write('/workspace/data.txt', 'Hello, World!\nLine 2\nLine 3')
# Read the file
content = sandbox.files.read('/workspace/data.txt')
print(content)
# Output:
# Hello, World!
# Line 2
# Line 3
sandbox.kill()
Expected Output:Hello, World!
Line 2
Line 3
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Write a file first
await sandbox.files.write('/workspace/data.txt', 'Hello, World!\nLine 2\nLine 3');
// Read the file
const content = await sandbox.files.read('/workspace/data.txt');
console.log(content);
// Output:
// Hello, World!
// Line 2
// Line 3
await sandbox.kill();
Expected Output:Hello, World!
Line 2
Line 3
Reading Binary Files
Read binary files (images, PDFs, etc.) as bytes:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Generate a plot and save it
sandbox.run_code('''
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.savefig('/workspace/plot.png')
''')
# Read the binary image file
image_data = sandbox.files.read_bytes('/workspace/plot.png')
print(f"Image size: {len(image_data)} bytes")
# Save to local file
with open('local_plot.png', 'wb') as f:
f.write(image_data)
sandbox.kill()
Expected Output:import { Sandbox } from '@hopx-ai/sdk';
import * as fs from 'fs';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Generate a plot and save it
await sandbox.runCode(`
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.savefig('/workspace/plot.png')
`);
// Read the binary image file
const imageData = await sandbox.files.readBytes('/workspace/plot.png');
console.log(`Image size: ${imageData.length} bytes`);
// Save to local file
fs.writeFileSync('local_plot.png', imageData);
await sandbox.kill();
Expected Output:
Reading Code Files
Read and execute code files:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Write a Python script
sandbox.files.write('/workspace/script.py', '''
def greet(name):
return f"Hello, {name}!"
print(greet("World"))
''')
# Read and execute
script_content = sandbox.files.read('/workspace/script.py')
result = sandbox.run_code(script_content, language='python')
print(result.stdout) # "Hello, World!"
sandbox.kill()
Expected Output:import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Write a Python script
await sandbox.files.write('/workspace/script.py', `
def greet(name):
return f"Hello, {name}!"
print(greet("World"))
`);
// Read and execute
const scriptContent = await sandbox.files.read('/workspace/script.py');
const result = await sandbox.runCode(scriptContent, { language: 'python' });
console.log(result.stdout); // "Hello, World!"
await sandbox.kill();
Expected Output:
Reading Configuration Files
Read JSON, YAML, or other configuration files:
from hopx_ai import Sandbox
import json
sandbox = Sandbox.create(template="code-interpreter")
# Write a config file
sandbox.files.write('/workspace/config.json', '''
{
"api_key": "sk-123",
"debug": true,
"timeout": 30
}
''')
# Read and parse
config_content = sandbox.files.read('/workspace/config.json')
config = json.loads(config_content)
print(f"API key: {config['api_key']}")
print(f"Debug: {config['debug']}")
sandbox.kill()
Expected Output:API key: sk-123
Debug: True
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Write a config file
await sandbox.files.write('/workspace/config.json', `
{
"api_key": "sk-123",
"debug": true,
"timeout": 30
}
`);
// Read and parse
const configContent = await sandbox.files.read('/workspace/config.json');
const config = JSON.parse(configContent);
console.log(`API key: ${config.api_key}`);
console.log(`Debug: ${config.debug}`);
await sandbox.kill();
Expected Output:API key: sk-123
Debug: true
Reading Large Files
For large files, consider using timeouts:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Read large file with custom timeout
try:
content = sandbox.files.read('/workspace/large_file.txt', timeout=120)
print(f"Read {len(content)} characters")
except Exception as e:
print(f"Error reading file: {e}")
sandbox.kill()
Expected Output:import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Read large file (timeout handled by HTTP client)
try {
const content = await sandbox.files.read('/workspace/large_file.txt');
console.log(`Read ${content.length} characters`);
} catch (error) {
console.error(`Error reading file: ${error.message}`);
}
await sandbox.kill();
Expected Output:
Error Handling
Handle file reading errors:
from hopx_ai import Sandbox
from hopx_ai.errors import FileNotFoundError, FileOperationError
sandbox = Sandbox.create(template="code-interpreter")
try:
content = sandbox.files.read('/workspace/nonexistent.txt')
except FileNotFoundError:
print("File not found")
except FileOperationError as e:
print(f"File operation error: {e}")
# Check if file exists first
if sandbox.files.exists('/workspace/data.txt'):
content = sandbox.files.read('/workspace/data.txt')
print(content)
else:
print("File does not exist")
sandbox.kill()
Expected Output:File not found
File does not exist
import { Sandbox } from '@hopx-ai/sdk';
import { FileNotFoundError, FileOperationError } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
try {
const content = await sandbox.files.read('/workspace/nonexistent.txt');
} catch (error) {
if (error instanceof FileNotFoundError) {
console.error('File not found');
} else if (error instanceof FileOperationError) {
console.error(`File operation error: ${error.message}`);
}
}
// Check if file exists first
const exists = await sandbox.files.exists('/workspace/data.txt');
if (exists) {
const content = await sandbox.files.read('/workspace/data.txt');
console.log(content);
} else {
console.log('File does not exist');
}
await sandbox.kill();
Expected Output:File not found
File does not exist
Reading Multiple Files
Read multiple files in a loop:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Create multiple files
for i in range(3):
sandbox.files.write(f'/workspace/file_{i}.txt', f'Content {i}')
# Read all files
files = sandbox.files.list('/workspace')
for file in files:
if file.is_file and file.name.endswith('.txt'):
content = sandbox.files.read(file.path)
print(f"{file.name}: {content}")
sandbox.kill()
Expected Output:file_0.txt: Content 0
file_1.txt: Content 1
file_2.txt: Content 2
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Create multiple files
for (let i = 0; i < 3; i++) {
await sandbox.files.write(`/workspace/file_${i}.txt`, `Content ${i}`);
}
// Read all files
const files = await sandbox.files.list('/workspace');
for (const file of files) {
if (file.isFile && file.name.endsWith('.txt')) {
const content = await sandbox.files.read(file.path);
console.log(`${file.name}: ${content}`);
}
}
await sandbox.kill();
Expected Output:file_0.txt: Content 0
file_1.txt: Content 1
file_2.txt: Content 2
Complete Example
Here’s a complete example showing file reading workflow:
from hopx_ai import Sandbox
import json
sandbox = Sandbox.create(template="code-interpreter")
# Generate some files
sandbox.run_code('''
import json
import matplotlib.pyplot as plt
# Create data file
data = {"values": [1, 2, 3, 4, 5]}
with open('/workspace/data.json', 'w') as f:
json.dump(data, f)
# Create plot
plt.plot([1, 2, 3, 4, 5])
plt.savefig('/workspace/plot.png')
# Create text file
with open('/workspace/readme.txt', 'w') as f:
f.write("Generated files:\n- data.json\n- plot.png")
''')
# Read all generated files
print("📄 Reading generated files:\n")
# Read JSON data
json_content = sandbox.files.read('/workspace/data.json')
data = json.loads(json_content)
print(f"Data: {data}")
# Read binary plot
plot_data = sandbox.files.read_bytes('/workspace/plot.png')
print(f"Plot size: {len(plot_data)} bytes")
# Read text file
readme = sandbox.files.read('/workspace/readme.txt')
print(f"\nReadme:\n{readme}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Generate some files
await sandbox.runCode(`
import json
import matplotlib.pyplot as plt
# Create data file
data = {"values": [1, 2, 3, 4, 5]}
with open('/workspace/data.json', 'w') as f:
json.dump(data, f)
# Create plot
plt.plot([1, 2, 3, 4, 5])
plt.savefig('/workspace/plot.png')
# Create text file
with open('/workspace/readme.txt', 'w') as f:
f.write("Generated files:\\n- data.json\\n- plot.png")
`);
// Read all generated files
console.log('📄 Reading generated files:\n');
// Read JSON data
const jsonContent = await sandbox.files.read('/workspace/data.json');
const data = JSON.parse(jsonContent);
console.log(`Data: ${JSON.stringify(data)}`);
// Read binary plot
const plotData = await sandbox.files.readBytes('/workspace/plot.png');
console.log(`Plot size: ${plotData.length} bytes`);
// Read text file
const readme = await sandbox.files.read('/workspace/readme.txt');
console.log(`\nReadme:\n${readme}`);
await sandbox.kill();
Best Practices
1. Check File Existence
Use files.exists() before reading to avoid errors, or handle FileNotFoundError appropriately.
2. Use Appropriate Method
Use read() for text files and read_bytes() for binary files (images, PDFs, etc.).
3. Set Timeouts for Large Files
For large files, set appropriate timeouts to avoid connection timeouts.
4. Handle Encoding
Text files are automatically decoded. Binary files return raw bytes.
5. Read from Allowed Paths
Only read from allowed paths like /workspace and /tmp. System directories may be restricted.
Next Steps