Practice: Merge Two Files

Practice: Merge Two Files

This exercise combines reading and writing in one function.

Exercise

  1. Define a function named merge_files with three parameters: first_path, second_path, and output_path.
  2. It writes the full content of the first file, then the full content of the second, into the output file — replacing whatever the output file held.

If a.txt contains one and a newline, and b.txt contains two and a newline, the output file contains one, newline, two, newline.

Run your code to see the output, then press Submit.

Hints

  • Read both inputs into strings, then open the output with "w" and write both.
  • No line processing needed — read and write the whole contents.

Tests

import unittest


class TestMergeFiles(unittest.TestCase):
    def setUp(self):
        with open("test_a.txt", "w") as file:
            file.write("one\n")
        with open("test_b.txt", "w") as file:
            file.write("two\n")

    def test_output_holds_both_in_order(self):
        merge_files("test_a.txt", "test_b.txt", "test_out.txt")
        with open("test_out.txt") as file:
            self.assertEqual(file.read(), "one\ntwo\n")

    def test_existing_output_is_replaced(self):
        with open("test_out.txt", "w") as file:
            file.write("stale\n")
        merge_files("test_a.txt", "test_b.txt", "test_out.txt")
        with open("test_out.txt") as file:
            self.assertEqual(file.read(), "one\ntwo\n")

    def test_inputs_are_unchanged(self):
        merge_files("test_a.txt", "test_b.txt", "test_out.txt")
        with open("test_a.txt") as file:
            self.assertEqual(file.read(), "one\n")
def merge_files(first_path, second_path, output_path):
    with open(first_path) as file:
        first_content = file.read()
    with open(second_path) as file:
        second_content = file.read()
    with open(output_path, "w") as file:
        file.write(first_content)
        file.write(second_content)


with open("a.txt", "w") as file:
    file.write("one\n")
with open("b.txt", "w") as file:
    file.write("two\n")

merge_files("a.txt", "b.txt", "merged.txt")
with open("merged.txt") as file:
    print(file.read())
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.