Python Program to Merge Two Files

« Previous Program Next Program »

Merge Two Files in Python

To merge two files in python, you have to ask from user to enter name of the first and second file, and then ask a file name to create a file to place the merged content of the two file into this newly created file.

To merge the content of first and second file and put all the merged content from first and second file into the third file, you have to open the first and second file to read content of both the file, and then finally store the merged content of both files into another third file to successfully perform the merging of two files into another file.

Python Programming Code to Merge Two Files

Following python program ask from user to enter first and second file name, then to create a file to enter or place the merged content of first and second file into this file as shown here in this program:

# Python Program - Merge Two Files
import shutil
while True:
	print("Enter 'x' for exit.")
	filename1 = input("Enter first file name: ")
	filename2 = input("Enter second file name: ")
	if filename1 == 'x':
		filename3 = input("Create a new file to merge content of two file inside this file: ")
		print("Merging the content of two file in",filename3)
		with open(filename3, "wb") as wfd:
			for f in [filename1, filename2]:
				with open(f, "rb") as fd:
					shutil.copyfileobj(fd, wfd, 1024*1024*10)
		print("Content merged successfully.!")
		print("Want to see ? (y/n): ")
		check = input()
		if check == 'n':
			c = open(filename3, "r")

Here is the sample run of the above python program to illustrates how to merge two files to store the content of these files into another file. This is the first snapshot:

python merge two files

This is the second snapshot:

merge two files in python

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:

« Previous Program Next Program »


Quick Links
Signup - Login - Give Online Test