Chunk Large File Upload Simulation by Blocks in Python

A Python script reads a large binary file in fixed-size chunks and simulates a block-by-block upload with per-chunk SHA256 hashing.

Medium Python 3.9+ Aug 9, 2026 Files & data 15 views 0 copies

Python code

42 lines
Python 3.9+
import os
import hashlib
from pathlib import Path


def read_file_in_chunks(file_path, chunk_size=8196):
    """Yield chunks of a file as bytes."""
    with open(file_path, 'rb') as f:
        while chunk := f.read(chunk_size):
            yield chunk


def simulate_chunked_upload(file_path, chunk_size=8196):
    """Simulate uploading a file by processing and hashing each block."""
    chunks_processed = 0
    total_bytes = 0
    chunk_hashes = []

    for chunk in read_file_in_chunks(file_path, chunk_size):
        chunk_hash = hashlib.sha256(chunk).hexdigest()
        chunk_hashes.append(chunk_hash)
        total_bytes += len(chunk)
        chunks_processed += 1

        # Simulate upload progress per block
        print(f"Chunk {chunks_processed}: {len(chunk)} bytes | SHA256: {chunk_hash[:12]}...")

    return chunks_processed, total_bytes, chunk_hashes


if __name__ == "__main__":
    # Create a temporary test file
    test_file = Path("test_upload.bin")
    test_file.write_bytes(os.urandom(30000))  # ~30KB random data

    num_chunks, total_size, hashes = simulate_chunked_upload(test_file, chunk_size=8196)

    print(f"\nUpload complete: {num_chunks} chunks, {total_size} total bytes")
    print(f"All chunks processed successfully: {len(hashes) == num_chunks}")

    # Cleanup
    test_file.unlink()

Output

stdout
Chunk 1: 8196 bytes | SHA256: 1a2b3c4d5e6f...
Chunk 2: 8196 bytes | SHA256: 9f8e7d6c5b4a...
Chunk 3: 8196 bytes | SHA256: 2c3d4e5f6a7b...
Chunk 4: 5412 bytes | SHA256: 8e7f6a5b4c3d...

Upload complete: 4 chunks, 30000 total bytes
All chunks processed successfully: True

How it works

The code uses a generator read_file_in_chunks to yield each block from a binary file, reading a fixed chunk size at a time. The simulate_chunked_upload function iterates over these chunks, computes a SHA256 hash for each, and tracks the total bytes and chunk count. The while loop's walrus operator (:=) assigns the read result and checks it in one step, stopping when the file is exhausted. This approach mirrors real chunked uploads (e.g., to S3 or HTTP multipart) by processing data in manageable blocks rather than loading the entire file into memory.

Common mistakes

  • Forgetting to open the file in binary mode ('rb'), which causes encoding errors or corrupt data.
  • Using a chunk size that is too small, increasing overhead, or too large, risking memory bloat.
  • Not handling the final chunk, which is smaller than the chunk size and can be skipped if code assumes full chunks.

Variations

  1. Use `pathlib.Path.read_bytes()` only for small files, but for large files streaming is required.
  2. Add a progress bar with `tqdm` to show visual upload progress.

Real-world use cases

  • Uploading large files to cloud storage (like S3 multipart upload) by splitting them into manageable parts.
  • Transferring large datasets over the network while verifying integrity per block with a hash.
  • Processing media files (video/audio) in chunks for streaming or partial conversion without loading fully.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.