Python Program to merge two files into a third file
Let the given two files be file1.txt
and file2.txt
. Our Task is to merge both files into third file say file3.txt. The following are steps to merge.
- Open file1.txt and file2.txt in read mode.
- Open file3.txt in write mode.
- Read the data from file1 and add it in a string.
- Read the data from file2 and concatenate the data of this file to the previous string.
- Write the data from string to file3
- Close all the files
Note: To successfully run the below program file1.txt and file2.txt must exist in the same folder.
Suppose the text files file1.txt
and file2.txt
contain the following data.
file1.txt
file2.txt
Below is the implementation.
# Python program to # demonstrate merging # of two files data = data2 = "" # Reading data from file1 with open ( 'file1.txt' ) as fp: data = fp.read() # Reading data from file2 with open ( 'file2.txt' ) as fp: data2 = fp.read() # Merging 2 files # To add the data of file2 # from next line data + = "\n" data + = data2 with open ( 'file3.txt' , 'w' ) as fp: fp.write(data) |
Output:
Using for loop
The above approach can be shortened using for loop. The following are steps to merge.
- Create a list containing filenames.
- Open the file3 in write mode.
- Iterate through the list and open each file in read mode.
- Read the data from files and simultaneously write the data in file3.
- Close all the files
Below is the implementation.
# Python program to # demonstrate merging of # two files # Creating a list of filenames filenames = [ 'file1.txt' , 'file2.txt' ] # Open file3 in write mode with open ( 'file3.txt' , 'w' ) as outfile: # Iterate through list for names in filenames: # Open each file in read mode with open (names) as infile: # read the data from file1 and # file2 and write it in file3 outfile.write(infile.read()) # Add '\n' to enter data of file2 # from next line outfile.write( "\n" ) |
Output:
Last Updated on November 13, 2021 by admin