Program to merge two files into a third file using Python

Introduction

The task is to merge the content of two files(say file1 and file2) into third file file3.

Program to merge two files into a third file using Python File 1

Program to merge two files into a third file using Python File 2

Program

Approach 1

readftxtFile = readstxtFile = "" 
with open('firstFile.txt') as readFile: 
    readftxtFile = readFile.read() 
with open('secFile.txt') as readFile: 
    readstxtFile = readFile.read() 
readftxtFile += "\n"
readftxtFile += readstxtFile 
with open ('outputFile.txt', 'w') as readFile: 
    readFile.write(readftxtFile)
readFile.close()

Output:

Program to merge two files into a third file using Python Output 1

Approach 2

readFiles = ['firstFile.txt', 'secFile.txt'] 
with open('outputFile.txt', 'w') as writeFile: 
    for file in readFiles: 
        with open(file) as inputFile: 
            writeFile.write(inputFile.read()) 
        writeFile.write("\n")

Output

Program to merge two files into a third file using Python Output 2

Explanation

Approach 1:

  • Open the two content files in read mode and third file in write mode.
  • Read the lines of first file and store it in a variable temp.
  • Read the lines of second file and concatenate it to temp.
  • Write the data to third file.
  • Close the files.

Approach 2:

  • Assign the filename to a list variable.
  • Open the third file in write mode.
  • Iterate through the list variable and open the files in read mode to read the lines.
  • Read the lines and append the lines to third file simultaneously.
  • Close the files.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.