Checksum a Large File in Chunks

Hard ⏱ 18 min 25% acceptance ★★★★☆ 4.3
Large files must not be loaded whole. Write byte_sum(path) that opens a file in binary mode and returns the sum of all byte values, reading in 4096-byte chunks with the classic while + read(size) loop that stops on an empty result.

Examples

Example 1
Input
byte_sum('data.bin')  # file bytes: 0x01 0x02
Output
3
Explanation

Bytes 1 and 2 sum to 3.

Constraints

  • Open with 'rb'.
  • Never call read() without a size.
  • Loop ends when read returns b"".

Topics

File Handlingbinary modechunked reading

Companies

DropboxGoogleCisco

Hints

Hint 1

Iterating a bytes object yields integers already.

Hint 2

while chunk := f.read(4096): is the modern idiom.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.