Python program to combine two files into a third file



Let the given two files be file1.txt and file2.txt . Our task — combine both files into a third file, say file3.txt. Here are the steps to merge.

  1. Open file1.txt and file2.txt in read mode.
  2. Open file3.txt in write mode.
  3. Read data from file1 and append it to a line.
  4. Read data from file2 and concatenate data from this file with the previous line.
  5. Write data from a line to file3
  6. Close all files

Note. For the program below to run successfully, file1.txt and file2.txt must be 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 for
# demonstrate the merge
# from two files

 

data = data2 = ""

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

 
# Combine 2 files
# Add data from file2
# from next line

data + = ""

data + = data2

 

with open ( ` file3.txt` , `w` ) as fp:

fp.write (data)

Output:

Usage for a loop

The above approach can be shortened with a for loop. Below are the steps to merge.

  1. Create a list containing the file names.
  2. Open file3 in write mode.
  3. Loop through the list and open each file in read mode.
  4. Reading data from files and simultaneously writing data to file3.
  5. Close all files

Below is the implementation.

# Python program for
# demonstrate the merge
# two files

  
# Create a list of filenames

filenames = [ `file1.txt` , ` file2.txt` ]

 < / code> 
# Open file3 in write mode

with open ( ` file3.txt` , `w` ) as outfile:

  

# Loop through the list

for names in filenames:

 

# Open each file in Reading View

with open (names) as infile:

 

# read data from file1 and

# file2 and write it to file3

  outfile.write (infile.read ())

 

# Add & # 39; / n & # 39; to enter file data2

# from next line

outfile.write ( "" )

Output: