Python | Combine two text files

To merge two files in Python, we ask the user to enter the name of the main and second file and create a new file to put the merged content of the two data into this newly created file.

To complete this task, we should import libraries shutil & amp;  pathlib . You can install libraries using this command —

 pip install shutil pip install pathlib 

Also place two text files on your desktop.

First text file:

Second text file:

Below is the Python implementation —

import shutil

from pathlib import Path


firstfile = Path ( r `C: UsersSohomDesktopGFG.txt` )

secondfile = Path (r `C: UsersSohomDesktopCSE.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 ( "The 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 .close ()


Updated merged text file: