Python | Merge two text files

Given two text files, the task is to merge the data and store in a new text file. Let’s see how can we do this task using Python.

To merge two files in Python, we are asking user to enter the name of the primary and second file and make a new file to put the unified content of the two data into this freshly created file.

In order to do this task, we have to import shutil & pathlib libraries. You can install the libraries using this command –

pip install shutil
pip install pathlib

Also, place the two text files on the Desktop.

First text file:
Organized Folder

Second text file:
Organized Folder

Below is the Python implementation –

filter_none

edit
close

play_arrow

link
brightness_4
code

import shutil
from pathlib import Path
   
firstfile = Path(r'C:\Users\Sohom\Desktop\GFG.txt')
secondfile = Path(r'C:\Users\Sohom\Desktop\CSE.txt')
  
newfile = input("Enter the name of the new file: ")
print()
print("The merged content of the 2 files will be in", newfile)
  
with open(newfile, "wb") as wfd:
  
    for f in [firstfile, secondfile]:
        with open(f, "rb") as fd:
            shutil.copyfileobj(fd, wfd, 1024 * 1024 * 10)
  
print("\nThe content is merged successfully.!")
print("Do you want to view it ? (y / n): ")
  
check = input()
if check == 'n':
    exit()
else:
    print()
    c = open(newfile, "r")
    print(c.read())
    c.close()

chevron_right


Output:
Organized Folder

The updated merged text file:
Organized Folder



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.