Change language

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:

Python | Combine two text files _files: Questions

Python | Combine two text files File handling: Questions


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Best laptop for Zoom


Best laptop for Minecraft


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method