> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# File Operations

> File operations resource for reading, writing, and managing files in HopX sandboxes using the Python SDK. Complete reference for the Files class including methods for reading, writing, listing, uploading, downloading, and watching files. Includes code examples for all file operations and error handling.

**Version:** 0.3.0\
**Last Verified:** 2025-01-27\
**Package:** `hopx-ai` on [PyPI](https://pypi.org/project/hopx-ai/)

## Overview

The `Files` resource provides file operations for sandboxes. Access it via the `files` property on a `Sandbox` instance. All file operations are synchronous and work with both text and binary files.

The `Files` resource is lazy-loaded, meaning it's only initialized when first accessed.

## Access

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")
files = sandbox.files  # Lazy-loaded
```

## Methods

### `read`

Read text file contents.

```python theme={null}
files.read(path, *, timeout=None) -> str
```

**Parameters:**

* `path` (`str`): File path to read
* `timeout` (`int`, optional): Request timeout in seconds

**Returns:** `str` - File contents as string

**Raises:**

* `FileNotFoundError`: File does not exist
* `FileOperationError`: Read operation failed

**Example:**

```python theme={null}
content = sandbox.files.read("/workspace/script.py")
print(content)
```

**Expected Output:**

```
print('Hello, World!')
```

**See Also:**

* [API: Read File](/api/vm-agent/read-file)

***

### `read_bytes`

Read binary file contents.

```python theme={null}
files.read_bytes(path, *, timeout=None) -> bytes
```

**Parameters:**

* `path` (`str`): File path to read
* `timeout` (`int`, optional): Request timeout

**Returns:** `bytes` - File contents as bytes

**Example:**

```python theme={null}
image_data = sandbox.files.read_bytes("/workspace/image.png")
with open("local_image.png", "wb") as f:
    f.write(image_data)
```

***

### `write`

Write text file contents.

```python theme={null}
files.write(path, content, mode='0644', *, timeout=None) -> None
```

**Parameters:**

* `path` (`str`): File path to write
* `content` (`str`): Text content to write
* `mode` (`str`, optional): File permissions (default: `'0644'`)
* `timeout` (`int`, optional): Request timeout

**Raises:**

* `FileOperationError`: Write operation failed

**Example:**

```python theme={null}
sandbox.files.write("/workspace/hello.txt", "Hello, World!")
```

**Expected Output:**

```
File written successfully
```

**See Also:**

* [API: Write File](/api/vm-agent/write-file)

***

### `write_bytes`

Write binary file contents.

```python theme={null}
files.write_bytes(path, content, mode='0644', *, timeout=None) -> None
```

**Parameters:**

* `path` (`str`): File path to write
* `content` (`bytes`): Binary content to write
* `mode` (`str`, optional): File permissions
* `timeout` (`int`, optional): Request timeout

**Example:**

```python theme={null}
with open("local_file.bin", "rb") as f:
    data = f.read()
sandbox.files.write_bytes("/workspace/remote_file.bin", data)
```

***

### `list`

List directory contents.

```python theme={null}
files.list(path='/workspace', *, timeout=None) -> List[FileInfo]
```

**Parameters:**

* `path` (`str`, optional): Directory path (default: `'/workspace'`)
* `timeout` (`int`, optional): Request timeout

**Returns:** `List[FileInfo]` - List of file/directory information objects

**Example:**

```python theme={null}
items = sandbox.files.list("/workspace")
for item in items:
    if item.is_directory:
        print(f"Directory: {item.name}")
    else:
        print(f"File: {item.name} ({item.size} bytes)")
```

**Expected Output:**

```
File: hello.txt (13 bytes)
Directory: my_project
File: script.py (42 bytes)
```

**See Also:**

* [API: List Files](/api/vm-agent/list-files)

***

### `exists`

Check if file or directory exists.

```python theme={null}
files.exists(path, *, timeout=None) -> bool
```

**Parameters:**

* `path` (`str`): File or directory path
* `timeout` (`int`, optional): Request timeout

**Returns:** `bool` - `True` if exists, `False` otherwise

**Example:**

```python theme={null}
if sandbox.files.exists("/workspace/config.json"):
    content = sandbox.files.read("/workspace/config.json")
```

**Expected Output:**

```
File exists, content read successfully
```

**See Also:**

* [API: File Exists](/api/vm-agent/file-exists)

***

### `remove`

Delete file or directory.

```python theme={null}
files.remove(path, *, timeout=None) -> None
```

**Parameters:**

* `path` (`str`): File or directory path to delete
* `timeout` (`int`, optional): Request timeout

**Raises:**

* `FileNotFoundError`: Path does not exist
* `FileOperationError`: Delete operation failed

<Warning>
  This operation is irreversible. Directories are deleted recursively.
</Warning>

**Example:**

```python theme={null}
sandbox.files.remove("/workspace/temp_file.txt")
```

**Expected Output:**

```
File removed successfully
```

**See Also:**

* [API: Remove File](/api/vm-agent/remove-file)

***

### `mkdir`

Create directory.

```python theme={null}
files.mkdir(path, *, timeout=None) -> None
```

**Parameters:**

* `path` (`str`): Directory path to create
* `timeout` (`int`, optional): Request timeout

**Raises:**

* `FileOperationError`: Directory creation failed

**Example:**

```python theme={null}
sandbox.files.mkdir("/workspace/my_project")
sandbox.files.write("/workspace/my_project/main.py", "print('Hello')")
```

**Expected Output:**

```
Directory created successfully
File written successfully
```

***

### `upload`

Upload file from local filesystem to sandbox.

```python theme={null}
files.upload(local_path, remote_path, *, timeout=None) -> None
```

**Parameters:**

* `local_path` (`str`): Local file path
* `remote_path` (`str`): Remote file path in sandbox
* `timeout` (`int`, optional): Request timeout

**Example:**

```python theme={null}
sandbox.files.upload("./local_script.py", "/workspace/script.py")
```

**Expected Output:**

```
File uploaded successfully
```

***

### `download`

Download file from sandbox to local filesystem.

```python theme={null}
files.download(remote_path, local_path, *, timeout=None) -> None
```

**Parameters:**

* `remote_path` (`str`): Remote file path in sandbox
* `local_path` (`str`): Local file path
* `timeout` (`int`, optional): Request timeout

**Example:**

```python theme={null}
sandbox.files.download("/workspace/output.txt", "./local_output.txt")
```

**Expected Output:**

```
File downloaded successfully
```

***

## Examples

### Example 1: Basic File Operations

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Write a file
sandbox.files.write("/workspace/hello.py", "print('Hello, World!')")

# Read it back
content = sandbox.files.read("/workspace/hello.py")
print(content)

# Execute it
result = sandbox.run_code("exec(open('/workspace/hello.py').read())")
print(result.stdout)

sandbox.kill()
```

**Expected Output:**

```
print('Hello, World!')
Hello, World!
```

### Example 2: Working with Directories

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Create directory structure
sandbox.files.mkdir("/workspace/my_project")
sandbox.files.mkdir("/workspace/my_project/src")

# Write files
sandbox.files.write("/workspace/my_project/src/main.py", "print('Main')")
sandbox.files.write("/workspace/my_project/README.md", "# My Project")

# List directory
items = sandbox.files.list("/workspace/my_project")
for item in items:
    print(f"{item.name}: {'dir' if item.is_directory else 'file'}")

sandbox.kill()
```

**Expected Output:**

```
src: dir
README.md: file
```

### Example 3: File Upload/Download

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Upload local file
sandbox.files.upload("./local_script.py", "/workspace/remote_script.py")

# Process it in sandbox
result = sandbox.run_code("exec(open('/workspace/remote_script.py').read())")

# Download result
sandbox.files.write("/workspace/output.txt", result.stdout)
sandbox.files.download("/workspace/output.txt", "./local_output.txt")

sandbox.kill()
```

### Example 4: Binary File Operations

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Read binary file
image_data = sandbox.files.read_bytes("/workspace/image.png")

# Process it (example: get size)
size = len(image_data)
print(f"Image size: {size} bytes")

# Write binary data
sandbox.files.write_bytes("/workspace/copy.png", image_data)

sandbox.kill()
```

***

## FileInfo Model

The `list()` method returns `FileInfo` objects with the following properties:

* `name` (`str`): File or directory name
* `path` (`str`): Full path
* `size` (`int`): Size in bytes
* `is_directory` (`bool`): Whether it's a directory
* `permissions` (`str`): File permissions
* `modified_time` (`datetime`): Last modification time
* `is_file` (`bool`): Convenience property (opposite of `is_directory`)
* `size_kb` (`float`): Size in kilobytes
* `size_mb` (`float`): Size in megabytes

***

## Related Classes

* **[Sandbox](/sdk/python/sandbox)** - Main sandbox class
* **[Commands](/sdk/python/commands)** - Command execution resource
* **[Models](/sdk/python/models)** - Data models including `FileInfo`

## See Also

* [Core Concepts: Files](/core-concepts/files) - Learn about file operations
* [Sandbox Class](/sdk/python/sandbox) - Access files via `sandbox.files`

## Related

* **[Reading Files](/core-concepts/filesystem/reading)** - Learn about reading files
* **[Writing Files](/core-concepts/filesystem/writing)** - Learn about writing files
* **[Listing Files](/core-concepts/filesystem/listing)** - List directory contents
* **[API: File Operations](/api/vm-agent/read-file)** - VM Agent API endpoints

## Next Steps

* Learn about [Reading Files](/core-concepts/filesystem/reading) to access file contents
* Explore [Writing Files](/core-concepts/filesystem/writing) to create files
* Review [Uploading Files](/core-concepts/filesystem/uploading) for local file transfers
* **[CLI File Operations](/cli/commands/files)** - Use file operations from the command line
