Python Practice › File Handling Programs › Program 25
Merge two files
Write a Python program to read two files and write their contents into a new file.
Output
Hello from part 1 Hello from part 2
Approach
- Open the output once and copy each input into it.
Solution
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.