# Reading and writing files

https://virtx.sh/docs/tutorials/reading-writing-files/

Put files into a sandbox, get what it wrote back out, and move, copy, or remove files in it, without running a command.

Your code can read and write a sandbox's files directly, without running a command such as `cat` or `cp` in the sandbox.
Paths are relative to the sandbox's root, so leave out the leading `/`: `etc/hostname` means `/etc/hostname`.

> **Note:**
> [Volumes](https://virtx.sh/docs/tutorials/mounting-volumes/) have the same file API.
> Every call on this page also works on a volume's files, and needs no sandbox running.

## Put a file in, and get one out

This writes an input file into the sandbox, runs a command on it, and reads what the command wrote:

**Python**

```python
await sandbox.create_dir_all("work")
await sandbox.write_file("work/input.txt", "one two three\n")

await sandbox.exec(["sh", "-c", "wc -w < /work/input.txt > /work/count.txt"]).complete()

print(await sandbox.read_text("work/count.txt"))
```

**Node.js**

```js
await sandbox.createDirAll('work')
await sandbox.writeFile('work/input.txt', 'one two three\n')

await sandbox.exec(['sh', '-c', 'wc -w < /work/input.txt > /work/count.txt']).complete()

console.log(await sandbox.readText('work/count.txt'))
```

**Rust**

```rust
use virtx::Files;

sandbox.create_dir_all("work").await?;
sandbox.write_file("work/input.txt", "one two three\n", None).await?;

let cmd = ["sh", "-c", "wc -w < /work/input.txt > /work/count.txt"];
sandbox.exec(&SandboxExecArgs::new(cmd)).complete(false).await?;

println!("{}", sandbox.read_text("work/count.txt").await?);
```

`write_file` writes a whole file from a string (as UTF-8) or from bytes. The parent directory must exist, or the call fails with `409`. `create_dir_all` creates a directory and any missing parents, like `mkdir -p`.
`read_text` reads a whole UTF-8 file. `read_file` reads bytes: the whole file, or a range starting at an `offset`.

## Look around

`read_dir` lists a directory, each entry with its `name` and `metadata`.
`stat_file` returns a path's metadata: its size, when it was last modified, and its `etag`.
`exists`, `is_file` and `is_dir` check whether a path exists, is a file, or is a directory.

**Python**

```python
for entry in await sandbox.read_dir("work"):
    print(entry.name, entry.metadata.size)

if await sandbox.is_file("work/count.txt"):
    meta = await sandbox.stat_file("work/count.txt")
    print(meta.size, meta.etag)
```

**Node.js**

```js
for (const entry of await sandbox.readDir('work')) {
  console.log(entry.name, entry.metadata.size)
}

if (await sandbox.isFile('work/count.txt')) {
  const meta = await sandbox.statFile('work/count.txt')
  console.log(meta.size, meta.etag)
}
```

**Rust**

```rust
for entry in sandbox.read_dir("work").await? {
    println!("{} {}", entry.name, entry.metadata.size);
}

if sandbox.is_file("work/count.txt").await? {
    let meta = sandbox.stat_file("work/count.txt").await?;
    println!("{} {:?}", meta.size, meta.etag);
}
```

## Move, copy, and remove

`rename_file` moves a file or a directory. `copy_file` copies a file, or a directory and everything in it.
Both fail with `412` if the destination exists, unless you set `overwrite`.
`remove_file` removes a file, or a directory and everything in it. It fails if the path doesn't exist, unless you set `missing_ok`, like `rm -f`.

**Python**

```python
await sandbox.copy_file("work/count.txt", "work/count.bak")
await sandbox.rename_file("work/count.bak", "work/old.txt", overwrite=True)
await sandbox.remove_file("work", missing_ok=True)
```

**Node.js**

```js
await sandbox.copyFile('work/count.txt', 'work/count.bak')
await sandbox.renameFile('work/count.bak', 'work/old.txt', true)
await sandbox.removeFile('work', true)
```

**Rust**

```rust
sandbox.copy_file("work/count.txt", "work/count.bak", false).await?;
sandbox.rename_file("work/count.bak", "work/old.txt", true).await?;
sandbox.remove_file("work", true).await?;
```

## Write only if unchanged

To avoid overwriting someone else's change, pass the file's `etag` from `stat_file` as `if_match` to `write_file`. The write succeeds only if the file still has that `etag`.
If the file changed in the meantime, the write fails with `412` and the file is left as it was.

**Python**

```python
meta = await sandbox.stat_file("notes.txt")
await sandbox.write_file("notes.txt", "updated\n", if_match=meta.etag)
```

**Node.js**

```js
const meta = await sandbox.statFile('notes.txt')
await sandbox.writeFile('notes.txt', 'updated\n', meta.etag)
```

**Rust**

```rust
let meta = sandbox.stat_file("notes.txt").await?;
sandbox.write_file("notes.txt", "updated\n", meta.etag.as_deref()).await?;
```

If two writes with the same `etag` arrive at the same time, one succeeds and the other fails with `412`. After a `412`, read the file again and retry.
The server checks the `etag` before it starts writing, and again just before it replaces the file.

## Reading files from an idle sandbox

The server reads a sandbox's files through its VM. If the server stopped the VM because the sandbox was idle, reading a file boots the VM again first, which takes time.
To read a finished task's output without booting a VM, have the task write its output to a volume, and read it from the volume. See [Mounting volumes](https://virtx.sh/docs/tutorials/mounting-volumes/).

## Troubleshooting

1. **`409`, from `write_file` or `create_dir`**

   **Cause:** The parent directory does not exist.

   **Fix:** Make it first with `create_dir_all`.

2. **`405`, from `create_dir_all`**

   **Cause:** A file is at that path.

   **Fix:** Remove or rename the file.

3. **`404`, from `remove_file`**

   **Cause:** Nothing is at that path.

   **Fix:** Pass `missing_ok` to treat that as done.

4. **`412`, from `copy_file` or `rename_file`**

   **Cause:** The destination exists.

   **Fix:** Pass `overwrite`.

5. **`412`, from `write_file` with `if_match`**

   **Cause:** The file changed since its `etag` was read.

   **Fix:** Read it again with `stat_file` and retry.

6. **An error that mentions UTF-8, from `read_text`**

   **Cause:** The file is not UTF-8 text.

   **Fix:** Read its bytes with `read_file`.

7. **`400`**

   **Cause:** The path has `.` or `..` in it, or leads outside the sandbox's root.

   **Fix:** Use a path inside the root.

8. **`403`**

   **Cause:** A write to a volume mounted read-only, or a move or remove of the root directory itself.

   **Fix:** Mount the volume read-write, or use a path under the root.

9. **`409`, `ended`**

   **Cause:** The sandbox's VM has stopped permanently.

   **Fix:** Create another sandbox. Keep outputs on a [volume](https://virtx.sh/docs/tutorials/mounting-volumes/) so they survive this.

## Next

- [Mounting volumes](https://virtx.sh/docs/tutorials/mounting-volumes/): keep files after a sandbox is removed, and share them between sandboxes.
- [Running commands](https://virtx.sh/docs/tutorials/running-commands/): run what reads and writes the files.
