# 读写设备文件

文件读写接口可让您轻松的使用该功能从设备上传或者下载文件，支持大文件的下载和上传，您可以使用相关接口将文件下载到本地或者内存，将内存或者本地的文件上传到设备之上，同时包括删除文件，修改文件权限以及获取文件信息等功能。
对于不存在或者无权限的操作的文件，调用将会引起**原生**的 Python 异常如 `OSError`、`FileNotFoundError`。

## 下载文件到本地

该接口可以将设备上的文件下载到本地，下述样例中，会将设备上的文件 `/verity_key` 的内容下载到当前电脑的 `my_file.txt` 文件中，注意下载的文件不会保留原始权限信息。

```python
d.download_file("/verity_key", "my_file.txt")
```

```python
>>> d.download_file("/adb_keys", "my_file.txt")
name: "adb_keys"
path: "/adb_keys"
st_mode: 33188
st_atime: 1230768000
st_mtime: 1230768000
st_ctime: 1230768000
st_size: 2202
```

```python
>>> result = d.download_file("/adb_keys", "my_file.txt")
>>> print (result.st_mtime)
1230768000
>>> os.chmod("my_file.txt", result.st_mode)
```

## 下载文件到内存

该接口可以将设备上的文件下载到内存之中（通过 BytesIO）。

```python
from io import BytesIO
fd = BytesIO()

d.download_fd("/verity_key", fd)
print (fd.getvalue())
```


## 下载文件到描述符

该接口可以将设备上的文件下载到文件描述符，注意文件需要以 `wb` 二进制模式打开。

```python
fd = open("my_file.txt", "wb")
d.download_fd("/verity_key", fd)
```

## 上传文件到设备

该接口可以将本地的文件上传到设备之上，示例中，意义为将本地的 `测试文件.txt` 上传到设备的 `/data/usr/file.txt` 文件之中，上传文件同样不会保留原始的权限信息。

```python
d.upload_file("测试文件.txt", "/data/usr/file.txt")
```

```python
>>> d.upload_file("file.txt", "/data/usr/file.txt")
name: "file.txt"
path: "/data/usr/file.txt"
st_mode: 33184
st_atime: 1230768000
st_mtime: 1230768000
st_ctime: 1230768000
```

```python
>>> result = d.upload_file("file.txt", "/data/usr/file.txt")
>>> print (result.st_size)
0
```

## 从内存上传文件

以下示例，将内存中的文件内容通过 BytesIO 上传到设备的 `/data/usr/file.txt` 文件。

```python
from io import BytesIO
d.upload_fd(BytesIO(b"fileContent"), "/data/usr/file.txt")
```

## 从描述符上传文件

以下示例，将本地的文件 `myfile.txt` 内容通过 fd 描述符上传到设备的 `/data/usr/file.txt` 文件，注意本地的文件需要使用 `rb` 二进制模式打开。

```python
fd = open("myfile.txt", "rb")
d.upload_fd(fd, "/data/usr/file.txt")
```

## 删除设备文件

此接口用于删除设备上的文件。

```python
d.delete_file("/data/usr/file.txt")
```

```python
>>> d.delete_file("/data/usr/file.txt")
True
```

```python
>>> d.delete_file("/adb_keys")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
OSError: [Errno 30] Read-only file system
```

## 修改文件权限

此接口用于修改设备上的文件权限。

```python
d.file_chmod("/data/usr/file.txt", mode=0o777)
```

```python
>>> d.file_chmod("/data/usr/file.txt", mode=0o777)
name: "file.txt"
path: "/data/usr/file.txt"
st_mode: 33279
st_atime: 1230768000
st_mtime: 1230768000
st_ctime: 1230768000
```

```python
>>> result = d.file_chmod("/data/usr/file.txt", mode=0o777)
>>> print (oct(result.st_mode))
0o100777
```

## 获取文件信息

此接口用于获取设备上文件的相关信息。

```python
d.file_stat("/data/usr/file.txt")
```

```python
>>> d.file_stat("/data/usr/file.txt")
name: "file.txt"
path: "/data/usr/file.txt"
st_mode: 33279
st_atime: 1230768000
st_mtime: 1230768000
st_ctime: 1230768000
```

```python
>>> result = d.file_stat("/data/usr/file.txt")
>>> print (result.name)
'file.txt'
```