Python Program to merge two files into a third file



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.

 

  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.

# 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:
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.

# 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:
Python-file-handling-file3

Last Updated on November 13, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs