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.
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:
Finally, I hope that this tutorial has helped you to understand the topic of “how to merge two files in Python”.
- You can also read:
setdefault() method in Python.
- rindex() method in Python.
- class and instance attributes in Python
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?
Can you please elaborate about merging of two files with same header in python as well?
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?
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