Merge Two Sorted Files
Advanced · Stretch · from Python File Handling: Read, Write, and Process Files
From the lesson: Python File Handling: Read, Write, and Process Files
Imagine you have a notebook where you write down important things. You open it, read what's inside, add new notes, and then close it. Python works with files the same way.
Read the lessonTwo files each hold one word per line, in alphabetical order. Write a function merge_sorted(first, second, out) that writes all the words from both into the file out, in alphabetical order, each on its own line ending with "\n", and returns how many lines it wrote.
import io
out = io.StringIO()
merge_sorted(io.StringIO("apple\ncherry\n"), io.StringIO("banana\ndate\n"), out) # 4
out.getvalue() # 'apple\nbanana\ncherry\ndate\n'The three arguments are open files: io.StringIO objects here, or files from open() on your computer. Read the inputs one line at a time with readline(), without loading a whole file. The last line of a file may not end with "\n". Some of the tests are hidden.
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| import io out = io.StringIO() count = merge_sorted(io.StringIO("apple\ncherry\n"), io.StringIO("banana\ndate\n"), out) print(count) print(repr(out.getvalue())) | 4 'apple\nbanana\ncherry\ndate\n' |
| import io out = io.StringIO() print(merge_sorted(io.StringIO("kiwi\nlime\n"), io.StringIO(""), out)) print(repr(out.getvalue())) | 2 'kiwi\nlime\n' |
More File Handling exercises
- Read and Print File ContentsBeginner
- Predict the Read OutputBeginner
- Write and Read BackIntermediate
- Fix the File Reading BugIntermediate
- Line Number FormatterAdvanced
All Python exercises · 50 practice problems · File I/O & Data Formats quiz