Merge Two Files

Merge Two Files

Write a function that combines the contents of two files into a third.

merge_two_files(path_a, path_b, out_path)

Read path_a and path_b, write "{a} {b}" (their contents, joined with a single space) to out_path, and return "done".

Examples

Given path_a containing "Hello" and path_b containing "World", out_path ends up containing "Hello World".


Walkthrough

Thinking it through

def merge_two_files(path_a, path_b, out_path):
    with open(path_a) as f:
        a = f.read()
    with open(path_b) as f:
        b = f.read()
    with open(out_path, "w") as f:
        f.write(f"{a} {b}")
    return "done"

Three separate with blocks, each doing one job: read path_a into a, read path_b into b, then write the combined result to out_path. Reusing the variable name f across all three blocks is fine — each with block's f only exists inside that block, so there's no conflict between them.

This extends the same read-then-write shape from Uppercase File to two input files instead of one: gather everything you need from the input files first (while they're each briefly open), then open the output file once you have both pieces ready to combine — rather than trying to juggle three files open simultaneously.

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