# Read and Write Files
<subtitle>Efficiently perform persistent storage and read operations for files within the sandbox.</subtitle>

## Environment Setup

Before using the SDK, please ensure that the `AGENTBOX_API_KEY` environment variable is configured.

>
> You can obtain your API key from the [Console API Keys page](https://console.ucloud.cn/modelverse/experience/api-keys).

```bash
export AGENTBOX_API_KEY=your_api_key
```

The file system is the core way for sandboxes to store state. The SDK provides a series of convenient methods to handle different types of data such as text and binary.

## Read File Contents

Use the `files.read()` method to retrieve file contents from a specified path.

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# Read text file
content = sandbox.files.read('/home/user/output.txt')
print(f"File content: {content}")
```

## Write Single File

Use the `files.write()` method to save data to the sandbox. If the parent directory of the target path does not exist, the SDK will automatically create it for you.

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# Write simple text
sandbox.files.write('/home/user/script.py', 'print("Hello from Sandbox")')

# Write binary data
sandbox.files.write('/home/user/data.bin', b'\x00\x01\x02\x03')
```

## Batch Write Multiple Files

To reduce network round-trip time (RTT), for multiple small files, it is recommended to use `write_files` for batch operations.

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

files_to_sync = [
    {"path": "config/app.conf", "data": "port=8080"},
    {"path": "data/sample.json", "data": '{"id": 1}'}
]

sandbox.files.write_files(files_to_sync)
```

---

>
> **Permission Note**: If you attempt to write files to protected system directories (such as `/etc`), please ensure your sandbox process has sudo permissions, or complete the operation using `commands.run` with commands like `sudo tee`.
