Read Files
Read file content directly from the sandbox as a string.
sandbox.read_file(
path: str,
encoding: str = "utf-8"
) -> str4MB Limit: Maximum file size is 4MB. For larger files, use download_file().
Parameters
pathstringrequiredAbsolute path in the sandbox to read from. Must start with /.
encodingstringText encoding for decoding file content. Default: "utf-8"
Returns
stringThe content of the file as a decoded string.
When to Use read_file vs download_file
| Feature | read_file() | download_file() |
|---|---|---|
| Size Limit | 4MB | Unlimited (streaming) |
| Return Type | String (in memory) | Boolean (saves to file) |
| Use Case | Quick reads, text files, configs | Large files, binary files, archives |
| Progress Tracking | No | Yes (callback) |
| Checksum Verification | No | Yes (optional) |
Basic Usage
from concave import sandbox
with sandbox() as sbx:
# Read a text file
content = sbx.read_file("/tmp/data.txt")
print(content)
# Read a JSON file
import json
json_content = sbx.read_file("/tmp/config.json")
config = json.loads(json_content)
print(config)Advanced Examples
Reading with Different Encodings
# Read a file with latin-1 encoding
content = sbx.read_file("/tmp/legacy.txt", encoding="latin-1")
# Read an ASCII file
content = sbx.read_file("/tmp/ascii.txt", encoding="ascii")Processing File Content
# Read and process a CSV file
csv_content = sbx.read_file("/tmp/data.csv")
lines = csv_content.strip().split("\n")
for line in lines:
columns = line.split(",")
print(columns)
# Read and parse YAML
import yaml
yaml_content = sbx.read_file("/tmp/config.yaml")
config = yaml.safe_load(yaml_content)Reading Code Files
# Read Python code
script = sbx.read_file("/tmp/script.py")
print("Script contents:")
print(script)
# Execute the script after reading
result = sbx.run(script)
print(result.stdout)Error Handling
from concave import (
sandbox,
SandboxFileNotFoundError,
SandboxValidationError,
SandboxPermissionDeniedError
)
with sandbox() as sbx:
try:
content = sbx.read_file("/tmp/data.txt")
print(content)
except SandboxFileNotFoundError as e:
print(f"File not found: {e.path}")
except SandboxValidationError as e:
print(f"Validation error: {e}")
except SandboxPermissionDeniedError as e:
print(f"Permission denied: {e.path}")Exceptions
SandboxFileNotFoundErrorRaised when the specified file doesn't exist in the sandbox.
SandboxValidationErrorRaised when the path is not absolute, file exceeds 4MB limit, or encoding is invalid.
SandboxPermissionDeniedErrorRaised when the sandbox doesn't have permission to read the file.
SandboxNotFoundErrorRaised when the sandbox no longer exists.
SandboxTimeoutErrorRaised when the read operation times out (typically after 35 seconds).
SandboxFileErrorBase exception for other file operation failures.