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:

STEP1:

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

STEP2:

Open the third file in the “WRITE” mode.

STEP3:

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

STEP4:

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

STEP5:

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

TEXT FILE1:

Merge two text files into one in Python

TEXT FILE2:

text file 2

CODE TO MERGE:

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

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”.

2 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?

    Thanks

  2. RKaur says:

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

Leave a Reply

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