Merge two files

EasyFile Handling Programs · 25 of 38

Write a Python program to read two files and write their contents into a new file.

Advertisement
Output
Hello from part 1
Hello from part 2

Approach

  1. Open the output once and copy each input into it.

Solution

Python
with open("part1.txt", "w") as f:    f.write("Hello from part 1\n")with open("part2.txt", "w") as f:    f.write("Hello from part 2\n") with open("merged.txt", "w") as out:    for name in ["part1.txt", "part2.txt"]:        with open(name) as f:            out.write(f.read())print(open("merged.txt").read())
Output
Hello from part 1
Hello from part 2

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Leave a Comment