How to merge multiple files into a single file in Python
You will sometimes have a situation where you have two or more files containing data and you desire to merge them into a single file. Here we will learn a Python program do accomplish this task.
Let us suppose we have 3 files named file1.txt, file2.txt, and file3.txt containing:
The goal is to merge them into a single file as shown below:
Let us write a Python program to first read these files. We embed the file opening and reading commands inside a for loop to cycle through these multiple files:
Here the loop cycles through the three files in the list called “myfiles”. For each of these files, represented by the variable “f”, we open the file and use “infile” as the file pointer variable. We then use the read() method to read the contents of “infile” and print them. Note that depending on the loop iteration, the variable “infile” refers to different files.
The output will be, as expected:
Now we are ready to write these contents into a new file. Let us call it “mergedfile.txt”. The updated program will be:
Note that we now embed the existing for loop inside a larger loop that opens “mergedfile.txt” in write mode and then instead of printing the contents to the standard output channel, we write them into the newfile.
If we run this program, you should see a new file called “mergedfile.txt” being created by the program. Let us open it and inspect its contents:
Oops! Looks like we didn’t print a newline after each file’s contents. Here is an updated program:
The new output will be as we expected:
You can extend this program to work on more files by simply updating the “myfiles” variable.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.