Reassemble File Parts into Original File Bytes in Python

Read sorted part files from a directory and concatenate their bytes into the original file.

Easy Python 3.9+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

36 lines
Python 3.9+
import os
import sys
from pathlib import Path

def reassemble_parts(parts_dir: Path, output_path: Path) -> int:
    """
    Reassemble file parts into the original file.

    Args:
        parts_dir: Directory containing the part files
        output_path: Path where the reassembled file will be written

    Returns:
        Number of bytes written
    """
    part_files = sorted(
        parts_dir.glob("part_*"),
        key=lambda p: int(p.stem.split("_")[1])
    )
    
    total_bytes = 0
    with open(output_path, "wb") as output:
        for part_file in part_files:
            with open(part_file, "rb") as part:
                data = part.read()
                output.write(data)
                total_bytes += len(data)
    
    return total_bytes

if __name__ == "__main__":
    parts_directory = Path("file_parts")
    output_file = Path("original_file.bin")
    
    bytes_written = reassemble_parts(parts_directory, output_file)
    print(f"Reassembled {len(list(parts_directory.glob('part_*')))} parts into {output_file} ({bytes_written} bytes)")

Output

stdout
Reassembled 3 parts into original_file.bin (1536 bytes)

How it works

The glob pattern part_* matches all part files in the directory. Sorting with a lambda on the numeric suffix ensures correct order — without numeric sorting, part_10 would come before part_2, corrupting the output. Reading each part in binary mode ('rb') preserves exact bytes. Writing to the output file in binary mode ('wb') ensures no text encoding issues. The total byte count is accumulated as parts are written, providing a verification metric.

Common mistakes

  • Sorting part files alphabetically instead of numerically, causing out-of-order reassembly.
  • Opening files in text mode instead of binary mode, which can corrupt non-text data.
  • Not handling missing part files or verifying all parts exist before writing.
  • Overwriting an existing output file without checking if it should be preserved.

Variations

  1. Use `Path.iterdir()` with a filter and a custom sort key for non-standard part names.
  2. Write parts in a streaming fashion to avoid loading the entire file into memory for large files.

Real-world use cases

  • Reassembling multi-part uploads from a cloud storage service that splits files into chunks.
  • Joining segmented log backups or database dumps stored across multiple files.
  • Reconstructing a large dataset file after transferring it in chunks over a network.

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.