Python Program to merge two files into a third file

Prerequisite: Reading and writing to a 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.

  1. Open file1.txt and file2.txt in read mode.
  2. Open file3.txt in write mode.
  3. Read the data from file1 and add it in a string.
  4. Read the data from file2 and concatenate the data of this file to the previous string.
  5. Write the data from string to file3
  6. 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
Python-file-handling-file1

file2.txt
Python-file-handling-file2

Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:
Python-file-handling-file3

Using for loop

The above approach can be shortened using for loop. The following are steps to merge.

  1. Create a list containing filenames.
  2. Open the file3 in write mode.
  3. Iterate through the list and open each file in read mode.
  4. Read the data from files and simultaneously write the data in file3.
  5. Close all the files

Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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")

chevron_right


Output:
Python-file-handling-file3




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.