# Python 文件读写

一种基于 sha256 的文件分片 hash 计算方式

```python
# -*- coding: UTF-8 -*-
import hashlib

def file_piece_sha256(in_file_path, piece_size):
    sha256 = hashlib.sha256()
    with open(in_file_path, "rb") as in_file:
        # TODO(You): 请在此实现 hash 计算
    return sha256.digest().hex()

if __name__ == '__main__':
    ret = file_piece_sha256('file_piece_sha256.py', 128)
    print("file hash is: ", ret)
```

请选出下列能**正确**实现TODO功能的选项。

## template

```python
import hashlib


def file_piece_sha256(in_file_path, piece_size):
    sha256 = hashlib.sha256()
    with open(in_file_path, "rb") as in_file:
        while True:
            piece = in_file.read(piece_size)
            if piece:
                sha256.update(piece.hex().encode('utf-8'))
            else:
                break
    return sha256.digest().hex()

if __name__ == '__main__':
    ret = file_piece_sha256('file_piece_sha256.py', 128)
    print("file hash is: ", ret)
```

## 答案

```python
while True:
    piece = in_file.read(piece_size)
    if piece:
        sha256.update(piece.hex().encode('utf-8'))
    else:
        break
```

## 选项

### A

```python
while True:
    piece = in_file.read(piece_size)
    if piece:
        sha256.update(piece.hex().encode('utf-8'))
    else:
        continue
```

### B

```python
while True:
    piece = in_file.readline(piece_size)
    if piece:
        sha256.update(piece.hex().encode('utf-8'))
    else:
        continue
```

### C

```python
while True:
    piece = in_file.read(piece_size)
    if piece:
        sha256.update(piece.encode('utf-8'))
    else:
        continue
```

### D

```python
while True:
    piece = in_file.read(piece_size)
    if piece:
        sha256.append(piece.encode('utf-8'))
    else:
        continue
```
