Reassemble File Parts into Original File Bytes in Python
Read sorted part files from a directory and concatenate their bytes into the original file.
Python code
36 linesimport 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
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
- Use `Path.iterdir()` with a filter and a custom sort key for non-standard part names.
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.