# 读写文件
<subtitle>通过 SDK 读取、写入、列出和删除 Volume 中的文件与目录。</subtitle>

## 读取文件

使用 `read_file()` 方法读取 Volume 中的文件。默认以文本形式返回，也可以通过 `format` 参数指定为 `bytes` 或 `stream`。

```python
from ucloud_sandbox import Volume

volume = Volume.connect('volume-id')

content = volume.read_file('/path/to/file')
print(content)

# 以字节形式读取
data = volume.read_file('/path/to/file', format='bytes')
```

## 写入文件

使用 `write_file()` 方法向 Volume 写入文件。文件不存在时会自动创建，已存在时会被覆盖。

```python
from ucloud_sandbox import Volume

volume = Volume.connect('volume-id')

volume.write_file('/path/to/file', 'file content')
```

## 创建目录

使用 `make_dir()` 方法在 Volume 中创建目录。

```python
from ucloud_sandbox import Volume

volume = Volume.connect('volume-id')

volume.make_dir('/path/to/dir')

# 使用 force 选项创建多级目录
volume.make_dir('/path/to/nested/dir', force=True)
```

## 列出目录内容

使用 `list()` 方法列出 Volume 中某个目录的内容。

```python
from ucloud_sandbox import Volume

volume = Volume.connect('volume-id')

entries = volume.list('/path/to/dir')
print(entries)
# [
#   VolumeEntryStat(name='file.txt', type='file', path='/path/to/dir/file.txt', size=13, ...),
#   VolumeEntryStat(name='subdir', type='directory', path='/path/to/dir/subdir', size=0, ...),
# ]
```

## 删除文件或目录

使用 `remove()` 方法删除 Volume 中的文件或目录。

```python
from ucloud_sandbox import Volume

volume = Volume.connect('volume-id')

# 删除文件
volume.remove('/path/to/file')

# 删除目录
volume.remove('/path/to/dir')
```
