How to Merge Sorted Chunk Files in Python
Merge multiple sorted text files into one sorted output file using a heap for efficient k-way merging.
Python code
47 linesimport heapq
def merge_sorted_chunks(chunks, output_path):
"""Merge multiple sorted iterables into single sorted output file."""
with open(output_path, "w") as out_f:
# Open all chunk files
handles = [open(chunk, "r") for chunk in chunks]
try:
# Heap of (value, index) tuples; value is current line
heap = []
for idx, fh in enumerate(handles):
line = fh.readline()
if line:
heap.append((line.strip(), idx))
heapq.heapify(heap)
while heap:
# Pop smallest value
value, idx = heapq.heappop(heap)
out_f.write(value + "\n")
# Read next line from the same chunk
nxt = handles[idx].readline()
if nxt:
heapq.heappush(heap, (nxt.strip(), idx))
finally:
for fh in handles:
fh.close()
if __name__ == "__main__":
# Demo: write three sorted chunk files
chunk_files = []
for i, data in enumerate([[1, 5, 9], [2, 6, 10], [3, 7, 11]]):
name = f"chunk_{i}.txt"
with open(name, "w") as f:
for num in data:
f.write(f"{num}\n")
chunk_files.append(name)
# Merge and display the result
output = "merged.txt"
merge_sorted_chunks(chunk_files, output)
print(f"Merged output from {chunk_files}:")
with open(output) as f:
print(f.read().strip())
Output
Merged output from ['chunk_0.txt', 'chunk_1.txt', 'chunk_2.txt']:
1
2
3
5
6
7
9
10
11
How it works
The heap (priority queue) keeps track of the smallest current value across all chunk files. Each pop retrieves the global minimum, writes it to output, and immediately refills from the same source file. This maintains O(log k) operations per item where k is the number of chunks. The solution is memory-efficient because it only holds one line per file in memory at a time.
Common mistakes
- Forgetting .strip() and writing leftover whitespace/newlines into the output
- Closing file handles manually instead of using context managers properly
- Assuming all chunks have equal length or handling empty chunks incorrectly
Variations
- Use file objects directly with itertools.chain with sorted() for small datasets
- Use external library like pandas.concat() for tabular data merge
Real-world use cases
- Merging sorted log files from multiple servers into a single time-ordered log stream.
- Combining sorted CSV segments from distributed processing jobs into one dataset.
- Building a merge phase for an external sort algorithm when data exceeds memory.
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.