Write Files
Write string content directly to sandbox files.
sandbox.write_file(
path: str,
content: str,
overwrite: bool = False,
encoding: str = "utf-8"
) -> bool4MB Limit: Maximum content size is 4MB. For larger files, use upload_file().
Parameters
pathstringrequiredAbsolute path in the sandbox where the file should be written. Must start with /. Parent directories will be created automatically if they don't exist.
contentstringrequiredString content to write to the file. The content will be encoded using the specified encoding before writing.
overwritebooleanWhether to overwrite the file if it already exists. Defaults to False. If False and the file exists, a SandboxFileExistsError is raised.
encodingstringText encoding for encoding content. Default: "utf-8"
Returns
boolReturns True if the write was successful.
When to Use write_file vs upload_file
| Feature | write_file() | upload_file() |
|---|---|---|
| Size Limit | 4MB | Unlimited (streaming) |
| Input Type | String (in memory) | File path (streams from disk) |
| Use Case | Generated content, configs, text | 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:
# Write a simple text file
sbx.write_file("/tmp/hello.txt", "Hello, World!")
# Write a JSON file
import json
data = {"name": "Alice", "age": 30}
sbx.write_file("/tmp/data.json", json.dumps(data, indent=2))
# Overwrite an existing file
sbx.write_file("/tmp/output.txt", "New content", overwrite=True)Advanced Examples
Writing with Different Encodings
# Write a file with latin-1 encoding
sbx.write_file("/tmp/legacy.txt", "Héllo Wörld", encoding="latin-1")
# Write an ASCII file
sbx.write_file("/tmp/ascii.txt", "Simple ASCII", encoding="ascii")Writing Configuration Files
import yaml
import toml
# Write YAML config
config = {"database": {"host": "localhost", "port": 5432}}
yaml_content = yaml.dump(config)
sbx.write_file("/tmp/config.yaml", yaml_content)
# Write TOML config
toml_content = toml.dumps(config)
sbx.write_file("/tmp/config.toml", toml_content)
# Write .env file
env_vars = "DATABASE_URL=postgres://localhost\nAPI_KEY=secret123"
sbx.write_file("/tmp/.env", env_vars)Writing Code Files
# Write a Python script
script = """
import sys
print("Hello from generated script!")
print(f"Python version: {sys.version}")
"""
sbx.write_file("/tmp/script.py", script)
# Execute the script
result = sbx.execute("python /tmp/script.py")
print(result.stdout)Nested Directories
# Parent directories are created automatically
sbx.write_file("/tmp/deep/nested/path/file.txt", "Content")
# Create multiple files in a structure
files = {
"/tmp/project/src/main.py": "print('main')",
"/tmp/project/src/utils.py": "def helper(): pass",
"/tmp/project/tests/test_main.py": "def test_main(): pass",
"/tmp/project/README.md": "# My Project"
}
for path, content in files.items():
sbx.write_file(path, content)Error Handling
from concave import (
sandbox,
SandboxFileExistsError,
SandboxValidationError,
SandboxInsufficientStorageError
)
with sandbox() as sbx:
try:
sbx.write_file("/tmp/data.txt", "Some content")
print("File written successfully")
except SandboxFileExistsError as e:
print(f"File already exists: {e.path}")
# Retry with overwrite
sbx.write_file("/tmp/data.txt", "Some content", overwrite=True)
except SandboxValidationError as e:
print(f"Validation error: {e}")
except SandboxInsufficientStorageError as e:
print(f"Out of storage space: {e}")Exceptions
SandboxFileExistsErrorRaised when the file already exists and overwrite=False.
SandboxValidationErrorRaised when the path is not absolute, content exceeds 4MB limit, or encoding is invalid.
SandboxPermissionDeniedErrorRaised when the sandbox doesn't have permission to write to the specified path.
SandboxInsufficientStorageErrorRaised when the sandbox has run out of storage space.
SandboxNotFoundErrorRaised when the sandbox no longer exists.
SandboxTimeoutErrorRaised when the write operation times out (typically after 35 seconds).
SandboxFileErrorBase exception for other file operation failures.