How to merge two txt files in python

MERGING TWO TEXT FILES IN PYTHON

when working with text files in Python, one common task is merging the contents of multiple files into a single file. This can be useful in  various contexts, such as combining data from different sources, consolidating logs, or simply organizing information more effectively.

In this blog post, We’ll walk through a step-by-step guide to merging two text files. You can use any of the IDE’s to run the code.

steps:

1)create the files:

First, you must create two text files and save them with the .txt extension. I have taken two files named fruitstextfile1 and flowerstextfile2

#fruitstextfile1
apple
banana
grapes
#flowerstextfile2
rose
jasmine
tulip
lilly
sunflower

2)you need to create a Python file

Then you must create a new Python file to merge the two text files and save it with the .py extension. Here I have used  the merge.py Python file

#merge.py
import os
files=[]
merged_data=""
while True:
    f_name=input("Enter the file name:")
    files.append(f_name)
    ans=input("Want to add another file?(y/n):").lower()
    if ans!='y' :
        break
for file in files:
    filename=file+'.txt'
    if os.path.isfile(filename):
        f=open(filename,mode='r',encoding='utf8')
        merged_data=merged_data+f.read()+'\n'
        f.close()
print(merged_data)

with open(input( "Enter final file name:")+'.txt',mode='x',encoding='utf8')as f:
    f.write(merged_data)

This Python file is used to merge the contents of two text files and produce the final file with all merged contents.

3)writing into a new file

Run the merge.py code to get the output

#output
Enter the file name:fruitstextfile1
Want to add another file?(y/n):y
Enter the file name:flowerstextfile2
Want to add another file?(y/n):n
apple
banana
grapes

rose
jasmine
tulip
lilly
sunflower

Enter final file name:plantstextfile

You need to follow  the above steps in output  to  merge and write the contents into  the final file

After entering a final filename, a new file will be created and the contents of two text files will be merged and displayed. I have  named the file as  plants-textfile

#plantstextfile
apple
banana
grapes

rose
jasmine
tulip
lilly
sunflower

So the final output is shown above.

 

 

 

 

.

 

Leave a Comment

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

Scroll to Top