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
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:
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:
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
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:
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
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
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()
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