Merge two text files into one in Python

In this tutorial, we are going to learn about merge two files in Python with some easy and understandable examples.

When most of us deal with files in Python we usually come across situations where we require to merge the contents of the two files into one.

In this tutorial, let us learn how to solve this problem.

Without any delay, let us see how to solve the above-specified problem.

Python merging of two text files:

In order to solve the above problem in Python we have to follow the below-mentioned steps:


Open the two files which we want to merge in the “READ” mode.


Open the third file in the “WRITE” mode.


Firstly, Read data from the first file and store it as a string.


Secondly, Read data from the second file and perform string concatenation.


Close all files and finally check the file into which the merging is done, for the successful merging or not.


Merge two text files into one in Python


text file 2


# Python program to merge two files 
  data = data2 = "" 
# Reading data from first file 
with open('file1.txt') as fp: 
    data = 
 with open('file2.txt') as fp: 
    data2 = 
# Merging two files into one another file 
data += "\n"
data += data2 
with open ('file3.txt', 'w') as fp: 

In the above code, we first read the data from both the files say “file1” AND “file2” which are shown in the above pictures and then we merge these contents into other file say “file3”.

After MERGING the file is:

After MERGING the file

Finally, I hope that this tutorial has helped you to understand the topic of “how to merge two files in Python”.

4 responses to “Merge two text files into one in Python”

  1. Tyrone says:

    Good Day,

    Thanks for the elegant way in which you solved this. I am very new to Python and struggling somewhat. How will you go about merging the two files and sort it in ascending order?


  2. RKaur says:

    Can you please elaborate about merging of two files with same header in python as well?

  3. Jonatan Garcia says:

    It does not seem to be a “merge” but an “append” of file2 to file1 into file3 as lines with same contents are duplicated. Any idea to deal with duplicates?

    • Saruque Ahamed Mollick says:

      You can use this one:
      seen_lines = set()
      outfile = open(outfilename, “w”)
      for line in open(infilename, “r”):
      if line not in seen_lines:

      You can use this piece of code

Leave a Reply

Your email address will not be published. Required fields are marked *