Kodeclik Blog


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.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2022. All rights reserved.