This exercise combines reading and writing in one function.
merge_files with three parameters: first_path, second_path, and output_path.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.
"w" and write both.read and write the whole contents.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())
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.